InfluxDB 연동

2021. 12. 26. 17:48Data

2.0 이상

https://github.com/influxdata/influxdb-client-java

 

GitHub - influxdata/influxdb-client-java: InfluxDB 2 JVM Based Clients

InfluxDB 2 JVM Based Clients. Contribute to influxdata/influxdb-client-java development by creating an account on GitHub.

github.com

# pom.xml 추가

	<!-- https://mvnrepository.com/artifact/org.influxdb/influxdb-java -->
	<dependency>
	    <groupId>com.influxdb</groupId>
	    <artifactId>influxdb-client-java</artifactId>
	    <version>4.0.0</version>
	</dependency>

org.influxdb.influxdbexception: {"code":"unauthorized","message":"unauthorized"}

2.0인데, pom.xml에 낮은 버전의 maven 추가하면 에러 발생

unsupported input type for mean aggregate: string

InfluxDB 웹화면에서 발생

string으로 된 값을 mean, median 등 그룹함수를 사용하면 에러 발생

아래 처럼 코딩을 변경해주고, 웹화면에서 Filter에 숫자만 체크해줘야 함

		Point point = Point.measurement("a")
				.addField("b",data.getString("b"))
				.addField("c",data.getBigDecimal("c"))
				.addField("d",rewarded.getBigDecimal("d"))
				.addField("e",rewarded.getBigDecimal("e"))
				.addField("f",rewarded.getBigDecimal("f"))
				.time(Instant.now().toEpochMilli(), WritePrecision.MS);

Java 연동

# 설치한 influxDB의 Java 연동 정보 참조

Data > Sources > Java

# pom.xml

<dependency>
  <groupId>com.influxdb</groupId>
  <artifactId>influxdb-client-java</artifactId>
  <version>3.1.0</version>
</dependency>

# Initialize the Client

package example;

import java.time.Instant;
import java.util.List;

import com.influxdb.annotations.Column;
import com.influxdb.annotations.Measurement;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.influxdb.query.FluxTable;

public class InfluxDB2Example {
  public static void main(final String[] args) {

    // You can generate an API token from the "API Tokens Tab" in the UI
    String token = 생성된 토큰;
    String bucket = 생성한 bucket;
    String org = 생성한 org;

    InfluxDBClient client = InfluxDBClientFactory.create("http://influxdb도메인:포트", token.toCharArray());
  }
}

# Write Data

Option 1

String data = "mem,host=host1 used_percent=23.43234543";

WriteApiBlocking writeApi = client.getWriteApiBlocking();
writeApi.writeRecord(bucket, org, WritePrecision.NS, data);

Option 2

Point point = Point
  .measurement("mem")
  .addTag("host", "host1")
  .addField("used_percent", 23.43234543)
  .time(Instant.now(), WritePrecision.NS);

WriteApiBlocking writeApi = client.getWriteApiBlocking();
writeApi.writePoint(bucket, org, point);

Option 3

Mem mem = new Mem();
mem.host = "host1";
mem.used_percent = 23.43234543;
mem.time = Instant.now();

WriteApiBlocking writeApi = client.getWriteApiBlocking();
writeApi.writeRecord(bucket, org, WritePrecision.NS, mem);



@Measurement(name = "mem")
public static class Mem {
  @Column(tag = true)
  String host;
  @Column
  Double used_percent;
  @Column(timestamp = true)
  Instant time;
}

# Execute a Flux query

String query = "from(bucket: \"nbminer\") |> range(start: -1h)";
List<FluxTable> tables = client.getQueryApi().query(query, org);

for (FluxTable table : tables) {
  for (FluxRecord record : table.getRecords()) {
    System.out.println(record);
  }
}

# Dispose the Client

client.close();

시간정보 강제로 셋팅하기

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");
String strDate = "2022020212:32:22";
Instant date = null;

try {
	date = sdf.parse(strDate).toInstant();
} catch(ParseException e) {
	e.printStackTrace();
}
						
Point point = Point
	.measurement("temp")
	.addTag("test", test)
	.addField("aa", aa)
	.time(date, WritePrecision.MS);

WriteApiBlocking writeApi = client.getWriteApiBlocking();
writeApi.writePoint(bucket, org, point);

출력할 때, 시간대 맞춰주기

http://daplus.net/java-%EC%9D%B8%EC%8A%A4%ED%84%B4%ED%8A%B8%EB%A5%BC-%EB%AC%B8%EC%9E%90%EC%97%B4%EB%A1%9C-%ED%98%95%EC%8B%9D%ED%99%94/

 

[java] 인스턴트를 문자열로 형식화 - 리뷰나라

새로운 java 8 time-api와 패턴을 사용하여 Instant to String을 형식화하려고합니다. Instant instant = ...; String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant); 위의 코드를 사용하면 지원되지 않는

daplus.net

String query = "from(bucket: \"nbminer\") |> range(start: -1h)";
List<FluxTable> tables = client.getQueryApi().query(query, org);

for (FluxTable table : tables) {
  for (FluxRecord record : table.getRecords()) {
    System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Seoul")).format(record.getTime()) + " "+ record.getField());
  }
}

field vs tag 차이

field는 filter의 '_field' 항목으로 나옴

tag는 filter의 항목으로 나옴

'Data' 카테고리의 다른 글

Flux 문법  (0) 2022.02.03
Influxdb 설치  (0) 2021.12.26
기상청 과거자로 URL  (0) 2019.11.18
기상청 과거 날씨 데이터  (0) 2019.11.13
기상청 API URL  (0) 2019.11.09