spring-boot2集成influxDB

自spring-boot 2.0开始,spring-boot-autoconfigure提供了influxdb的简单集成实现类InfluxDbAutoConfiguration. 该类生效条件为@ConditionalOnClass(InfluxDB.class),所以只要引入influxdb-java依赖,就会自动生效。

compile group: 'org.influxdb', name: 'influxdb-java', version: '2.16'

集成比较简单(influx本地windows版本1.6.2),代码如下:

package demo.influx;

import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * influxDB时序数据库,支持增查,不支持删改,删除可配置删除策略
 * @author tom
 */
@Slf4j
@SpringBootApplication
public class InfluxSpringApplicationDemo implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(InfluxSpringApplicationDemo.class, args);
    }


    @Autowired
    private InfluxDB influxDB;

    @Override
    public void run(String... args) throws Exception {

        influxDB.setDatabase("mydb");
        influxDB.write(
                Point.measurement("demo_api").tag("name", "hello")
                .addField("rt", 10).addField("times", 320)
                .build()
        );

        String line = Point.measurement("demo_api").tag("name", "hello")
                .addField("rt", 3).addField("times", 145)
                .build().lineProtocol();
        log.info("line protocol => {}", line);
        //retentionPolicy参数为自建的policy名称
        //create retention policy mydb_retention_policy on mydb duration 7d replication 1
        influxDB.write("mydb", "mydb_retention_policy", InfluxDB.ConsistencyLevel.QUORUM, line);
        //i 代表integer数据类型
        influxDB.write("mydb", "mydb_retention_policy", InfluxDB.ConsistencyLevel.ONE
                , "demo_api,name=hello rt=4i,times=34i");

        //默认查询是select * from mydb.autogen.demo_api
        QueryResult rs = influxDB.query(new Query("select * from demo_api", "mydb"));
        log.info("query result => {}", rs);
        if (!rs.hasError() && !rs.getResults().isEmpty()) {
            rs.getResults().forEach(System.out::println);
        }

        //查询select * from mydb.mydb_retention_policy.demo_api
        rs = influxDB.query(new Query("select * from mydb.mydb_retention_policy.demo_api", "mydb"));
        log.info("query result => {}", rs);
        if (!rs.hasError() && !rs.getResults().isEmpty()) {
            rs.getResults().forEach(System.out::println);
        }

    }
}

注意:在使用influx客户端查询插入结果时,由于自定义了retention policy,所以代码中插入的结果位于两个retention policy。

一个measurement(相当于table)内存储的记录可以属于多个retention policy,这个retention policy定义保留策略的,对于不同的策略虽然插入的measurement是同一个,但是数据会归属于插入时指定的policy。当查询不指定policy时,使用默认的autogen,所以在插入到同一个measurement不同的policy时要注意,查询要指定policy。

参考:spring-boot-features-influxdb

          doc-influxDb

你可能感兴趣的:(Java,Spring)