云服务器内容精选

  • 使用非SSL方式连接实例的Java代码示例 package influxdb; 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 demoNoSSL { public static void main(String[] args) { OkHttpClient.Builder client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .retryOnConnectionFailure(true); // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全; // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。 String username = System.getenv("EXAMPLE_USERNAME_ENV"); String password = System.getenv("EXAMPLE_PASSWORD_ENV"); final String serverURL = "http://127.0.0.1:8086", username = username, password = password; 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(); } }
  • 使用连接池方式连接实例的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)); // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全; // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。 String username = System.getenv("EXAMPLE_USERNAME_ENV"); String password = System.getenv("EXAMPLE_PASSWORD_ENV"); final String serverURL = "http://127.0.0.1:8086", username = username, password = password; 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(); } }
  • 使用SSL方式连接实例的Java代码示例 package influxdb; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; 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 org.apache.http.ssl.SSLContexts; import javax.net.ssl.*; public class demo { public static void main(String[] args) { OkHttpClient.Builder client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .retryOnConnectionFailure(true); client.sslSocketFactory(defaultSslSocketFactory(), defaultTrustManager()); client.hostnameVerifier(noopHostnameVerifier()); // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全; // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。 String username = System.getenv("EXAMPLE_USERNAME_ENV"); String password = System.getenv("EXAMPLE_PASSWORD_ENV"); final String serverURL = "https://127.0.0.1:8086", username = username, password = password; 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(); } private static X509TrustManager defaultTrustManager() { return new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } }; } private static SSLSocketFactory defaultSslSocketFactory() { try { SSLContext sslContext = SSLContexts.createDefault(); sslContext.init(null, new TrustManager[] { defaultTrustManager() }, new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } } private static HostnameVerifier noopHostnameVerifier() { return new HostnameVerifier() { @Override public boolean verify(final String s, final SSLSession sslSession) { return true;//true 表示使用ssl方式,但是不校验ssl证书,建议使用这种方式 } }; } }
  • 使用SSL方式连接实例的示例代码 from influxdb import InfluxDBClient client = InfluxDBClient(host=IP, port=****, username=****, password=****, ssl=True) client.get_list_database() host,port,username,password请以实际值为准。 ssl的值必须设置为True。 如果不设置ssl,或者ssl设置为False,则会报如下错误: InfluxDBClientError: 400: Client sent an HTTP request to an HTTPS server.
  • 使用非SSL方式连接实例的示例代码 from influxdb import InfluxDBClient client = InfluxDBClient(host=IP, port=****, username=****, password=****, ssl=False) client.get_list_database() 上述host,port,username,password请以实际值为准。
  • 使用CCM私有证书连接实例的示例代码 package main import ( "fmt" "io/ioutil" "crypto/tls" "crypto/x509" _ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod client "github.com/influxdata/influxdb1-client/v2" ) func main(){ pool := x509.NewCertPool() caCertPath := "/data/CA/agent/ca.crt" caCrt, err := ioutil.ReadFile(caCertPath) if err != nil { fmt.Println("ReadFile err:", err) return } pool.AppendCertsFromPEM(caCrt) // 此处是将ca.crt证书内嵌到程序中,也可以使用sudo cp {client}/ca.crt /etc/ssl/certs命令将证书添加到本机上。 c, err := client.NewHTTPClient(client.HTTPConfig{ Addr: "https://ip:port", Username: "******", Password: "******", TLSConfig: &tls.Config{ RootCAs: pool, InsecureSkipVerify: false, // false表示需要校验服务端的证书。 }, }) if err != nil { fmt.Println("Error creating InfluxDB Client: ", err.Error()) } q := client.NewQuery("select * from cpu","database","ns") if response, err := c.Query(q); err == nil && response.Error() == nil { fmt.Println("the result is: ",response.Results) } }
  • 使用非SSL方式连接实例的示例代码 package main import ( "fmt" _ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod client "github.com/influxdata/influxdb1-client/v2" ) func main(){ c, err := client.NewHTTPClient(client.HTTPConfig{ Addr: "http://ip:port", Username: "******", Password: "******", }) if err != nil { fmt.Println("Error creating InfluxDB Client: ", err.Error()) } q := client.NewQuery("select * from cpu","db0","ns") if response, err := c.Query(q); err == nil && response.Error() == nil { fmt.Println("the result is: ",response.Results) } }
  • 使用默认SSL证书连接实例的示例代码 package main import ( "fmt" _ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod client "github.com/influxdata/influxdb1-client/v2" ) func main(){ c, err := client.NewHTTPClient(client.HTTPConfig{ Addr: "https://ip:port", Username:"******", Password:"******", InsecureSkipVerify: true, // true表示不验证服务端的信息,可能存在被攻击的风险,建议设为false,具体请参见使用CCM私有证书连接实例的示例代码。 }) if err != nil { fmt.Println("Error creating InfluxDB Client: ", err.Error()) } q := client.NewQuery("select * from cpu","databases","ns") if response, err := c.Query(q); err == nil && response.Error() == nil { fmt.Println(response.Results) } }
  • 使用连接池方式连接实例的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(); } }
  • 使用SSL方式连接实例的Java代码示例 package influxdb; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; 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 org.apache.http.ssl.SSLContexts; import javax.net.ssl.*; public class demo { public static void main(String[] args) { OkHttpClient.Builder client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .retryOnConnectionFailure(true); client.sslSocketFactory(defaultSslSocketFactory(), defaultTrustManager()); client.hostnameVerifier(noopHostnameVerifier()); final String serverURL = "https://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(); } private static X509TrustManager defaultTrustManager() { return new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } }; } private static SSLSocketFactory defaultSslSocketFactory() { try { SSLContext sslContext = SSLContexts.createDefault(); sslContext.init(null, new TrustManager[] { defaultTrustManager() }, new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } } private static HostnameVerifier noopHostnameVerifier() { return new HostnameVerifier() { @Override public boolean verify(final String s, final SSLSession sslSession) { return true;//true 表示使用ssl方式,但是不校验ssl证书,建议使用这种方式 } }; } }
  • 使用非SSL方式连接实例的Java代码示例 package influxdb; 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 demoNoSSL { public static void main(String[] args) { OkHttpClient.Builder client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .retryOnConnectionFailure(true); 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(); } }