Springboot整合influxdb实现写入数据和查询操作

一.SpringBoot集成InfluxDB 

既然准备SpringBoot整合InfluxDB,想必你已经了解了InfluxDB的安装、配置、使用。

那么就直奔正文

        <!-- start influxdb-->
        <dependency>
            <groupId>com.influxdb</groupId>
            <artifactId>influxdb-client-java</artifactId>
            <version>6.7.0</version>
            <!--   &lt;!&ndash;排除okhttp3的依赖&ndash;&gt;-->
            <exclusions>
                <exclusion>
                    <groupId>com.squareup.okhttp3</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--   &lt;!&ndash; 重新指定okhttp3版本&ndash;&gt;-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>logging-interceptor</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.influxdb</groupId>
            <artifactId>influxdb-java</artifactId>
            <version>2.23</version> <!-- 确保使用最新版本 -->
        </dependency>
        <!-- end influxdb-->

有些依赖包确实不太理解,但是没有的话会报错。

配置YAML文件:

  influx:
    url: http://172.29.162.162:8086
    username: admin
    password: 12345678
    database: mydb
    token: uSHJ-papdr9uVOtcKaw4uIOIy9ar5B8BCCIbOs6bIPcqHDb0v_Nf6zNcBKXzD4ZwLg3CcqJ9yPUtDgHcEu4Ijw==

token:是创建mydb数据库时的秘钥。

连接方式:


    //@Value("${spring.influx.url}")
    private String Url = "http://172.29.162.155:8086"; //influxdb 访问的路径

    //@Value("${spring.influx.token}")
    private String Token = "uSHJ-papdr9uVOtcKaw4uIOIy9ar5B8BCCIbOs6bIPcqHDb0v_Nf6zNcBKXzD4ZwLg3CcqJ9yPUtDgHcEu4Ijw=="; //influxdb在webui建立库之后的秘钥

    //@Value("${spring.influx.username}")
    private String UserName = "admin"; //账户名

    //@Value("${spring.influx.database}")
    private String Bucket = "mydb"; //桶名

    public static List<InfluxDBClient> InfluxDBClientList = new ArrayList<>();

    @Bean
    //建立连接
    public InfluxDBClient getConnectInfluxDBClient() {

        InfluxDBClient influxDBClient = InfluxDBClientFactory.create(Url,
                Token.toCharArray(), UserName, Bucket);

        InfluxDBClientList.add(influxDBClient);

        return influxDBClient;
    }

InfluxDBClientList :管理连接的集合

实体类:

package com.example.demo.dto;

import com.influxdb.annotations.Column;
import com.influxdb.annotations.Measurement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.time.Instant;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true) //链表赋值
@Measurement(name = "influxdbDtoInfo")//在influx中的名称
public class InfluxdbDto {
    
    @Column(name = "device_id",tag = true)  //tag 为标识列
    private String deviceId;
    
    @Column(name = "vehicle_id") //字段值
    private double vehicleId;
    
    @Column(timestamp = true) //时间节点
    private Instant locationTime;
    
}

2.创建mapper层的接口调用方法:

1.查询:

    //查询influxDb中的数据信息
    public List<InfluxdbDto> getFluxTableInfluxDb(String deviceName) {

        //    "  |> filter(fn: (r) => r[\"device_id\"] == \"" + "" + deviceName + "\")\n" +
        //                "  |> keep(columns: [\"_time\", \"_value\", \"device_id\"]) \n" +
        String flux = "from(bucket: \"mydb\")  \n" +
                "  |> range(start: -7d)  \n" +
                "  |> filter(fn: (r) => r[\"_measurement\"] == \"influxdbDtoInfo\")  \n" +
                "  |> filter(fn: (r) => r[\"device_id\"] == \"" + "" + deviceName + "\")\n" +
                "  |> filter(fn: (r) => r[\"_field\"] == \"vehicle_id\")  \n" +
                "  |> aggregateWindow(every: 1s, fn: last, createEmpty: false)\n" +
                "  |> keep(columns: [\"_time\", \"_value\"]) \n" +
                "  |> map(fn: (r) => ({\n" + "locationTime: r._time,\n" + "vehicle_id: r._value}))\n" +
                "  |> yield(name: \"last\")";

        //flux查询的方法
        QueryApi queryApi = getConnectInfluxDBClient().getQueryApi();


        return queryApi.query(flux, InfluxdbDto.class);


       /* for (FluxTable fluxTable : s) {
            List<FluxRecord> records = fluxTable.getRecords();
            for (FluxRecord record : records) {
                Object value = record.getValueByKey("_value");
                System.out.println(value);
            }
        }*/
    }
QueryApi:这个类是在依赖里面包含了,调用其中的query是去查询influxdb的数据。作者在编写的时候,也考虑到了对象转化,我在这里也使用到了。flux:这个就相当于sql语句,keep函数指的是需要保留的字段,map函数将influxdb中的字段名进行重命名。重命名是要注意要跟实体类上的名称一样。
2.添加:
    //往influxdb添加数据的方法 单条数据的方法
    public void insertInfluxDbWrite(InfluxdbDto influxdbDto) {


        try {
            //写入单条
            WriteApiBlocking writeApiBlocking = InfluxDBClientList.get(0).getWriteApiBlocking();

            writeApiBlocking.writeMeasurement(WritePrecision.NS, influxdbDto);


        } catch (Exception e) {
            //重新连接一次
            getConnectInfluxDBClient();
            e.printStackTrace();
        }


    }

总结:

不论是使用哪种方式 都各有利弊 根据项目的需求 决定使用的方式

如有疑问或文中有误 可以私信

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值