Connecting to Server

This section introduces the method connect for connecting to DolphinDB server.

Syntax

public boolean connect(String hostName, int port, String userId, String password, String initialScript, boolean enableHighAvailability, String[] highAvailabilitySites, boolean reconnect, boolean enableLoadBalance, int tryReconnectNums)

Parameters

  • hostName: The host name.
  • port: The port number.
  • timeout (optional, default 3000): An int specifying both the maximum connection and read timeouts (in ms) for underlying API Socket connections.
    Note:
    From version 3.00.1.3 onwards, new timeout parameters connectTimeout and readTimeout are added. If set along with timeout, the values of connectTimeout and readTimeout take precedence.
  • connectTimeout (optional, default 3000): An int indicating the maximum connection timeout (in ms) for underlying API Socket connections.
  • readTimeout (optional, default 0): An int indicating the maximum read timeout (in ms) for underlying API Socket connections.
  • userId (optional, default ""): The user to log in.
  • password (optional, default ""): The password to log in.

    If the connection is established without specifying a user’s userId and password, the scripts will be executed with guest privileges. To connect to the server as an administrator, you can fill the administrator username and password. Alternatively, you can refer to the login method that will be introduced later.

  • initialScript (optional, default ""): The initialization script. To define and use user-defined functions in a Java client, you can pass the function definitions to initialScript. These functions do not required to be defined repeatedly every time a script is executed. The Java API provides an automatic reconnection mechanism, which will generate a new session after reconnection. If initialScript is specified, the Java API will automatically execute the script and re-register the functions required by subsequent scripts.
  • enableHighAvailability (optional, default false): A Boolean value indicating whether to enable high availability.
  • highAvailabilitySites (optional, default null): A String array specifying host names and port numbers for high availability.
  • reconnect (optional, default false): A Boolean value indicating whether to automatically reconnect to a single node after disconnection. Its behavior depends on enableHighAvailability; see below.
  • enableLoadBalance (optional): A Boolean value indicating whether to enable load balancing in HA mode. It can be set to true only when high availability is enabled. Load balancing is enabled by default in HA mode; explicitly set this parameter to false to disable it. This parameter is introduced since version 2.00.11.0.
  • tryReconnectNums: Number of reconnection attempts for each connection. If not specified, reconnection attempts are not limited. If specified, limited attempts are applied in HA and non-HA modes. In HA mode, cycles through each node once per attempt, up to tryReconnectNums cycles.

Note:

  • When enableHighAvailability=true, the API selects nodes as follows:

    • Candidate nodes:

      • If highAvailabilitySites is specified: The candidate nodes are the entry node (specified by hostName and port) and the nodes in the array.

      • If highAvailabilitySites is not specified:

        • With load balancing enabled: The candidate nodes are the entry node and the data nodes returned by getClusterPerf.

        • With load balancing disabled: The candidate nodes are the entry node and the data nodes and compute nodes returned by getClusterPerf.

    • Initial connection:

      • With load balancing enabled: The API first attempts to establish a connection to the entry node, followed by the nodes in highAvailabilitySites in array order. After successfully connecting and obtaining cluster information, it randomly selects a data node that meets the low-load criteria from the candidate nodes. If no data node meets the criteria, it randomly selects a candidate node. If the selected node differs from the current node, the API attempts to switch to it. The low-load criteria must all be met: memory usage below 80%, connections below 90% of the maximum, and average CPU load below 0.8. Compute nodes among the candidate nodes are excluded from low-load selection, but may still be connected to during random selection or reconnection.

      • With load balancing disabled: The API first attempts to connect to the entry node. If that fails and highAvailabilitySites is specified, it tries the other nodes in array order. After successfully connecting, it does not proactively switch nodes based on load.

    • Reconnection: With high availability enabled, the API reconnects automatically. After a connection is interrupted, it randomly selects a node from the existing candidate nodes. For some exceptions, such as a read timeout during a function call or upload, it first tries to reconnect to the original node; if that fails, it selects a candidate node at random. Reconnection does not refresh the cluster node list or evaluate node load. Data nodes and compute nodes have equal priority during random selection. reconnect controls single-node reconnection only when high availability is disabled.

  • The low-load selection described above is supported since version 1.30.22.2. In version 1.30.22.1 and earlier, the API randomly connects to an available node.

Note:
Since version 3.00.2.6, the DBConnection.connect method supports configuring connection parameters via ConnectConfig, offering a more flexible way to set parameters. For details, please refer to the example below.

Returns

A Boolean value indicating whether the connection has been established.

Example

The following example creates a DBConnection object and connects to DolphinDB server.

First, create a connection object and specify the high availability node array. Then perform the connection operation, passing the specified hostName, port, userId, and password. In this example, the initialization script parameter initialScript is clearAllCache(), which clears cached data, including data loaded into memory from partitioned tables and intermediate results of map-reduce tasks in distributed computing. High availability and automatic reconnection are enabled.

@Test
public void testConnect() throws IOException {
    DBConnection dbConnection = new DBConnection();
    String[] highAvailabilitySites = new String[]{"192.168.1.167:18921", "192.168.1.167:18922", "192.168.1.167:18923"};
    boolean success = dbConnection.connect("192.168.1.167", 18921, "admin", "123456", "clearAllCache();", true, highAvailabilitySites, true);
    System.out.println("connect result: " + success);
}

The following example shows how to configure the connection parameters via ConnectConfig:

@Test
public void testConnect() throws IOException {
    DBConnection dbConnection = new DBConnection();
    DBConnection.ConnectConfig connectConfig = DBConnection.ConnectConfig.builder()
            .hostName("192.168.1.167")
            .port(18921)
            .userId("admin")
            .password("123456")
            .initialScript("clearAllCache();")
            .enableHighAvailability(true)
            .highAvailabilitySites(new String[]{"192.168.1.167:18921", "192.168.1.167:18922", "192.168.1.167:18923"})
            .build();
    dbConnection.connect(connectConfig);
}

Throws

  • If the userId or password is incorrect:
    java.io.IOException: 192.168.1.167:18921
    Server response: 'RemoteRun[ctl18920] The user name or password is incorrect.' function: 'login'
  • If the target server IP or port is incorrect:
    java.net.SocketException: Connection reset

    If an error containing SocketException is reported during connect, check the IP and port first.

  • If the initialScript has errors, such as using an undefined variable x:
    java.io.IOException: 192.168.1.167:18922 Server response: 'Syntax Error: [line #1] Cannot recognize the token x' script: 'x'

    If the error starts with hostName_+":"+port_+" Server response: 'Syntax Error', the error occurs on the server.