Java源码示例:com.influxdb.client.InfluxDBClient
示例1
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org);
String flux = "from(bucket:\"my-bucket\") |> range(start: 0)";
QueryApi queryApi = influxDBClient.getQueryApi();
//
// Query data
//
List<FluxTable> tables = queryApi.query(flux);
for (FluxTable fluxTable : tables) {
List<FluxRecord> records = fluxTable.getRecords();
for (FluxRecord fluxRecord : records) {
System.out.println(fluxRecord.getTime() + ": " + fluxRecord.getValueByKey("_value"));
}
}
influxDBClient.close();
}
示例2
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org);
Flux flux = Flux.from("my-bucket")
.range(-30L, ChronoUnit.MINUTES)
.filter(Restrictions.and(Restrictions.measurement().equal("cpu")))
.limit(10);
QueryApi queryApi = influxDBClient.getQueryApi();
//
// Query data
//
List<FluxTable> tables = queryApi.query(flux.toString());
for (FluxTable fluxTable : tables) {
List<FluxRecord> records = fluxTable.getRecords();
for (FluxRecord fluxRecord : records) {
System.out.println(fluxRecord.getTime() + ": " + fluxRecord.getValueByKey("_value"));
}
}
influxDBClient.close();
}
示例3
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org, bucket);
//
// Write data
//
try (WriteApi writeApi = influxDBClient.getWriteApi()) {
//
// Write by POJO
//
Temperature temperature = new Temperature();
temperature.location = "south";
temperature.value = 62D;
temperature.time = Instant.now();
writeApi.writeMeasurement(WritePrecision.NS, temperature);
}
influxDBClient.close();
}
示例4
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org, bucket);
//
// Write data
//
try (WriteApi writeApi = influxDBClient.getWriteApi()) {
//
// Write by LineProtocol
//
String record = "temperature,location=north value=60.0";
writeApi.writeRecord(WritePrecision.NS, record);
}
influxDBClient.close();
}
示例5
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org);
//
// Query data
//
String flux = "from(bucket:\"my-bucket\") |> range(start: 0) |> filter(fn: (r) => r._measurement == \"temperature\")";
QueryApi queryApi = influxDBClient.getQueryApi();
//
// Map to POJO
//
List<Temperature> temperatures = queryApi.query(flux, Temperature.class);
for (Temperature temperature : temperatures) {
System.out.println(temperature.location + ": " + temperature.value + " at " + temperature.time);
}
influxDBClient.close();
}
示例6
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org, bucket);
//
// Write data
//
try (WriteApi writeApi = influxDBClient.getWriteApi()) {
//
// Write by Data Point
//
Point point = Point.measurement("temperature")
.addTag("location", "west")
.addField("value", 55D)
.time(Instant.now().toEpochMilli(), WritePrecision.MS);
writeApi.writePoint(point);
}
influxDBClient.close();
}
示例7
private static String findToken() throws Exception {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999",
"my-user", "my-password".toCharArray());
String token = influxDBClient.getAuthorizationsApi()
.findAuthorizations()
.stream()
.filter(authorization -> authorization.getPermissions().stream()
.map(Permission::getResource)
.anyMatch(resource ->
resource.getType().equals(PermissionResource.TypeEnum.ORGS) &&
resource.getId() == null &&
resource.getOrgID() == null))
.findFirst()
.orElseThrow(IllegalStateException::new).getToken();
influxDBClient.close();
return token;
}
示例8
@BeforeEach
void setUp() throws Exception {
influxDB_URL = getInfluxDb2Url();
LOG.log(Level.FINEST, "InfluxDB URL: {0}", influxDB_URL);
InfluxDBClient influxDBClient = InfluxDBClientFactory.create(influxDB_URL, "my-user", "my-password".toCharArray());
organization = influxDBClient.getOrganizationsApi()
.findOrganizations().stream()
.filter(organization -> organization.getName().equals("my-org"))
.findFirst()
.orElseThrow(IllegalStateException::new);
influxDBClient.close();
try {
this.influxDBClient = InfluxDBClientReactiveFactory.create(influxDB_URL, "my-user", "my-password".toCharArray());
} catch (Exception e) {
Assertions.fail("Can't authorize via password", e);
}
}
示例9
@Override
public InfluxDBClient build(InfluxDBSinkConfig influxDBSinkConfig) {
val options = InfluxDBClientOptions.builder()
.url(influxDBSinkConfig.getInfluxdbUrl())
.authenticateToken(influxDBSinkConfig.getToken().toCharArray())
.org(influxDBSinkConfig.getOrganization())
.bucket(influxDBSinkConfig.getBucket())
.logLevel(LogLevel.valueOf(influxDBSinkConfig.getLogLevel().toUpperCase()))
.build();
InfluxDBClient influxDBClient = InfluxDBClientFactory.create(options);
if(influxDBSinkConfig.isGzipEnable()) {
influxDBClient.enableGzip();
}
return influxDBClient;
}
示例10
@Before
public void setUp() throws Exception {
// prepare a cpu Record
cpu = new Cpu();
cpu.setMeasurement("cpu");
timestamp = Instant.now().toEpochMilli();
cpu.timestamp = timestamp;
cpu.tags = Maps.newHashMap();
cpu.tags.put("host", "server-1");
cpu.tags.put("region", "us-west");
cpu.fields = Maps.newHashMap();
cpu.fields.put("model", "lenovo");
cpu.fields.put("value", 10);
influxSink = new InfluxDBSink();
influxSink.influxDBClientBuilder = mock(InfluxDBClientBuilder.class);
influxDBClient = mock(InfluxDBClient.class);
writeApi = mock(WriteApiBlocking.class);
when(influxSink.influxDBClientBuilder.build(any())).thenReturn(influxDBClient);
when(influxDBClient.getWriteApiBlocking()).thenReturn(writeApi);
}
示例11
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty("spring.influx2.url")
public InfluxDBClient influxDBClient() {
OkHttpClient.Builder okHttpBuilder;
if (builderProvider == null) {
okHttpBuilder = new OkHttpClient.Builder()
.readTimeout(properties.getReadTimeout())
.writeTimeout(properties.getWriteTimeout())
.connectTimeout(properties.getConnectTimeout());
} else {
okHttpBuilder = builderProvider.get();
}
InfluxDBClientOptions.Builder influxBuilder = InfluxDBClientOptions.builder()
.url(properties.getUrl())
.bucket(properties.getBucket())
.org(properties.getOrg())
.okHttpClient(okHttpBuilder);
if (StringUtils.hasLength(properties.getToken())) {
influxBuilder.authenticateToken(properties.getToken().toCharArray());
} else if (StringUtils.hasLength(properties.getUsername()) && StringUtils.hasLength(properties.getPassword())) {
influxBuilder.authenticate(properties.getUsername(), properties.getPassword().toCharArray());
}
return InfluxDBClientFactory.create(influxBuilder.build()).setLogLevel(properties.getLogLevel());
}
示例12
@Test
public void influxDBClientCanBeCustomized() {
this.contextRunner
.withPropertyValues("spring.influx2.url=http://localhost:8086/",
"spring.influx2.password:password", "spring.influx2.username:username")
.run(((context) -> Assertions.assertThat(context.getBeansOfType(InfluxDBClient.class))
.hasSize(1)));
}
示例13
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org, bucket);
WriteApiBlocking writeApi = influxDBClient.getWriteApiBlocking();
try {
//
// Write by LineProtocol
//
String record = "temperature,location=north value=60.0";
writeApi.writeRecord(WritePrecision.NS, record);
//
// Write by Data Point
//
Point point = Point.measurement("temperature")
.addTag("location", "west")
.addField("value", 55D)
.time(Instant.now().toEpochMilli(), WritePrecision.MS);
writeApi.writePoint(point);
//
// Write by POJO
//
Temperature temperature = new Temperature();
temperature.location = "south";
temperature.value = 62D;
temperature.time = Instant.now();
writeApi.writeMeasurement(WritePrecision.NS, temperature);
} catch (InfluxException ie) {
System.out.println("InfluxException: " + ie);
}
influxDBClient.close();
}
示例14
public static void main(final String[] args) {
String database = "telegraf";
String retentionPolicy = "autogen";
InfluxDBClient client = InfluxDBClientFactory.createV1("http://localhost:8086",
"username",
"password".toCharArray(),
database,
retentionPolicy);
System.out.println("*** Write Points ***");
try (WriteApi writeApi = client.getWriteApi()) {
Point point = Point.measurement("mem")
.addTag("host", "host1")
.addField("used_percent", 29.43234543);
System.out.println(point.toLineProtocol());
writeApi.writePoint(point);
}
System.out.println("*** Query Points ***");
String query = String.format("from(bucket: \"%s/%s\") |> range(start: -1h)", database, retentionPolicy);
List<FluxTable> tables = client.getQueryApi().query(query);
tables.get(0).getRecords()
.forEach(record -> System.out.println(String.format("%s %s: %s %s",
record.getTime(), record.getMeasurement(), record.getField(), record.getValue())));
client.close();
}
示例15
@Nonnull
@Override
public InfluxDBClient setLogLevel(@Nonnull final LogLevel logLevel) {
setLogLevel(this.loggingInterceptor, logLevel);
return this;
}
示例16
@Nonnull
@Override
public InfluxDBClient enableGzip() {
this.gzipInterceptor.enableGzip();
return this;
}
示例17
@Nonnull
@Override
public InfluxDBClient disableGzip() {
this.gzipInterceptor.disableGzip();
return this;
}
示例18
public InfluxDB2HealthIndicatorAutoConfiguration(final Map<String, InfluxDBClient> influxDBClients) {
this.influxDBClients = influxDBClients;
}
示例19
public InfluxDB2HealthIndicator(final InfluxDBClient influxDBClient) {
super("InfluxDBClient 2 health check failed");
Assert.notNull(influxDBClient, "InfluxDBClient must not be null");
this.influxDBClient = influxDBClient;
}
示例20
@Test
public void influxDBClientRequiresUrl() {
this.contextRunner.run((context) -> Assertions.assertThat(context.getBeansOfType(InfluxDBClient.class))
.isEmpty());
}
示例21
private int getReadTimeoutProperty(AssertableApplicationContext context) {
InfluxDBClient influxDB = context.getBean(InfluxDBClient.class);
Retrofit retrofit = (Retrofit) ReflectionTestUtils.getField(influxDB, "retrofit");
OkHttpClient callFactory = (OkHttpClient) retrofit.callFactory();
return callFactory.readTimeoutMillis();
}
示例22
@Bean
public InfluxDBClient influxDBClient() {
return mock(InfluxDBClient.class);
}
示例23
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org, bucket);
//
// Write data
//
try (WriteApi writeApi = influxDBClient.getWriteApi()) {
//
// Write by Data Point
//
Point point = Point.measurement("temperature")
.addTag("location", "west")
.addField("value", 55D)
.time(Instant.now().toEpochMilli(), WritePrecision.MS);
writeApi.writePoint(point);
//
// Write by LineProtocol
//
writeApi.writeRecord(WritePrecision.NS, "temperature,location=north value=60.0");
//
// Write by POJO
//
Temperature temperature = new Temperature();
temperature.location = "south";
temperature.value = 62D;
temperature.time = Instant.now();
writeApi.writeMeasurement( WritePrecision.NS, temperature);
}
//
// Query data
//
String flux = "from(bucket:\"my-bucket\") |> range(start: 0)";
QueryApi queryApi = influxDBClient.getQueryApi();
List<FluxTable> tables = queryApi.query(flux);
for (FluxTable fluxTable : tables) {
List<FluxRecord> records = fluxTable.getRecords();
for (FluxRecord fluxRecord : records) {
System.out.println(fluxRecord.getTime() + ": " + fluxRecord.getValueByKey("_value"));
}
}
influxDBClient.close();
}
示例24
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token, org);
//
// Query data
//
String flux = "from(bucket:\"my-bucket\") |> range(start: 0)";
QueryApi queryApi = influxDBClient.getQueryApi();
String csv = queryApi.queryRaw(flux);
System.out.println("CSV response: " + csv);
influxDBClient.close();
}
示例25
public static void main(final String[] args) {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", token);
DeleteApi deleteApi = influxDBClient.getDeleteApi();
try {
OffsetDateTime start = OffsetDateTime.now().minus(1, ChronoUnit.HOURS);
OffsetDateTime stop = OffsetDateTime.now();
deleteApi.delete(start, stop, "", "my-bucket", "my-org");
} catch (InfluxException ie) {
System.out.println("InfluxException: " + ie);
}
influxDBClient.close();
}
示例26
public static void main(final String[] args) throws Exception {
InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:9999", findToken().toCharArray());
Organization medicalGMBH = influxDBClient.getOrganizationsApi()
.createOrganization("Medical Corp" + System.currentTimeMillis());
//
// Create New Bucket with retention 1h
//
Bucket temperatureBucket = influxDBClient.getBucketsApi().createBucket("temperature-sensors", medicalGMBH);
//
// Add Permissions to read and write to the Bucket
//
PermissionResource resource = new PermissionResource();
resource.setId(temperatureBucket.getId());
resource.setOrgID(medicalGMBH.getId());
resource.setType(PermissionResource.TypeEnum.BUCKETS);
Permission readBucket = new Permission();
readBucket.setResource(resource);
readBucket.setAction(Permission.ActionEnum.READ);
Permission writeBucket = new Permission();
writeBucket.setResource(resource);
writeBucket.setAction(Permission.ActionEnum.WRITE);
Authorization authorization = influxDBClient.getAuthorizationsApi()
.createAuthorization(medicalGMBH, Arrays.asList(readBucket, writeBucket));
String token = authorization.getToken();
System.out.println("The token to write to temperature-sensors bucket " + token);
InfluxDBClient client = InfluxDBClientFactory.create("http://localhost:9999", token.toCharArray());
CountDownLatch countDownLatch = new CountDownLatch(1);
//
// Write data
//
try (WriteApi writeApi = client.getWriteApi(WriteOptions.builder()
.batchSize(5000)
.flushInterval(1000)
.backpressureStrategy(BackpressureOverflowStrategy.DROP_OLDEST)
.bufferLimit(10000)
.jitterInterval(1000)
.retryInterval(5000)
.build())) {
writeApi.listenEvents(WriteSuccessEvent.class, (value) -> countDownLatch.countDown());
//
// Write by POJO
//
Temperature temperature = new Temperature();
temperature.location = "south";
temperature.value = 62D;
temperature.time = Instant.now();
writeApi.writeMeasurement("temperature-sensors", medicalGMBH.getId(), WritePrecision.NS, temperature);
//
// Write by Point
//
Point point = Point.measurement("temperature")
.addTag("location", "west")
.addField("value", 55D)
.time(Instant.now().toEpochMilli(), WritePrecision.MS);
writeApi.writePoint("temperature-sensors", medicalGMBH.getId(), point);
//
// Write by LineProtocol
//
String record = "temperature,location=north value=60.0";
writeApi.writeRecord("temperature-sensors", medicalGMBH.getId(), WritePrecision.NS, record);
countDownLatch.await(2, TimeUnit.SECONDS);
}
//
// Read data
//
List<FluxTable> tables = client.getQueryApi().query("from(bucket:\"temperature-sensors\") |> range(start: 0)", medicalGMBH.getId());
for (FluxTable fluxTable : tables) {
List<FluxRecord> records = fluxTable.getRecords();
for (FluxRecord fluxRecord : records) {
System.out.println(fluxRecord.getTime() + ": " + fluxRecord.getValueByKey("_value"));
}
}
client.close();
influxDBClient.close();
}
示例27
@BeforeEach
void setUp() throws Exception {
super.setUp();
InfluxDBClient client = InfluxDBClientFactory.create(influxDB_URL, "my-user",
"my-password".toCharArray());
BucketRetentionRules bucketRetentionRules = new BucketRetentionRules();
bucketRetentionRules.setEverySeconds(3600);
bucket = client.getBucketsApi()
.createBucket(generateName("h2o"), bucketRetentionRules, organization);
//
// Add Permissions to read and write to the Bucket
//
PermissionResource resource = new PermissionResource();
resource.setOrgID(organization.getId());
resource.setType(PermissionResource.TypeEnum.BUCKETS);
resource.setId(bucket.getId());
Permission readBucket = new Permission();
readBucket.setResource(resource);
readBucket.setAction(Permission.ActionEnum.READ);
Permission writeBucket = new Permission();
writeBucket.setResource(resource);
writeBucket.setAction(Permission.ActionEnum.WRITE);
User loggedUser = client.getUsersApi().me();
Assertions.assertThat(loggedUser).isNotNull();
Authorization authorization = client.getAuthorizationsApi()
.createAuthorization(organization, Arrays.asList(readBucket, writeBucket));
token = authorization.getToken();
client.close();
influxDBClient.close();
influxDBClient = InfluxDBClientReactiveFactory.create(influxDB_URL, token.toCharArray());
queryClient = influxDBClient.getQueryReactiveApi();
}
示例28
InfluxDBClient build(InfluxDBSinkConfig config);