云数据库 GAUSSDB NOSQL-通过Java语言连接实例:使用连接池方式连接实例的Java代码示例

时间:2023-11-10 12:13:23

使用连接池方式连接实例的Java代码示例

package influxdb;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import java.util.concurrent.TimeUnit;

public class demoConnectionPool {
    public static void main(String[] args) {
        // 客户端连接池功能基于OkHttpClient实现
        OkHttpClient.Builder client = new OkHttpClient().newBuilder();
        client.connectTimeout(10, TimeUnit.SECONDS);
        client.readTimeout(10, TimeUnit.SECONDS);
        client.writeTimeout(10, TimeUnit.SECONDS);
        // 建议设为true,屏蔽部分连接错误,并自动进行重试
        client.retryOnConnectionFailure(true);
        // maxIdleConnections指连接池最多维护的未使用的Idle连接数量,默认值是5
        // 超过阈值的idle连接会由连接池关闭,关闭后sockets进入TIME_WAIT状态等待系统回收,该参数需根据实际连接数适当调整
        client.connectionPool(new ConnectionPool(5, 30, TimeUnit.SECONDS));

        final String serverURL = "http://127.0.0.1:8086", username = "root", password = "root";
        InfluxDB influxdb = InfluxDBFactory.connect(serverURL, username, password, client);

        // Create a database...
        String databaseName = "foo";

        influxdb.query(new Query("CREATE DATABASE " + databaseName, databaseName));
        influxdb.setDatabase(databaseName);

        // Write points to influxdb.
        influxdb.write(Point.measurement("bar")
                .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                .tag("location", "chengdu")
                .addField("temperature", 22)
                .build());

        // Query your data using InfluxQL.
        QueryResult queryResult = influxdb.query(new Query("SELECT * FROM bar", databaseName));

        // Close it if your application is terminating or you are not using it anymore.
        influxdb.close();
    }
}
support.huaweicloud.com/productdesc-nosql/nosql_09_0101.html