前言:

        网上的教程前篇一律,参差不齐,于是决定自己整理一下InfluxDB的基础安装。InfluxDB的基础介绍则不再赘述。

Docker安装InfluxFB

   


1.拉取InfluxDB1.8镜像 

[root@VM-12-13-centos ~]# docker pull influxdb1.8 #拉取镜像
.
.
.
[root@VM-12-13-centos ~]# docker images #查看所有镜像
REPOSITORY        TAG          IMAGE ID       CREATED        SIZE
influxdb          1.8          4a287b6e62f5   2 weeks ago    307MB

2.启动InfluxDB容器

[root@VM-12-13-centos ~]#  docker run -d -p 8086:8086 --name influxdb1.8 -v /data/docker/influxdb:/var/lib/influxdb --restart=always influxdb:1.8

[root@VM-12-13-centos ~]# docker ps # 查看运行中的容器

其中:

8086为InfluxDB的默认端口,记得打开安全组 

-v 将InfluxDB内部的data、meta、wal等文件挂载到宿主机

3.进入容器内部

[root@VM-12-13-centos ~]# dockers ps #查看运行中的容器
[root@VM-12-13-centos ~]# CONTAINER ID   IMAGE                     COMMAND                   CREATED        STATUS        PORTS                                                                                                                                                 NAMES
59d2f87e8efd   influxdb:1.8              "/entrypoint.sh infl…"   11 hours ago   Up 11 hours   0.0.0.0:8086->8086/tcp, :::8086->8086/tcp                                                                                                             influxdb

[root@VM-12-13-centos ~]# docker exec -it 59(容器id,可标识唯一即可) bin/bash

4.更改配置及创建用户

由于创建的实例默认不启用授权,也没有任何用户,所以我们需要开启连接授权以及创建管理员账号。

  • 更改配置以开启授权
cd /etc/influxdb/
apt-get update         # 更新apt-get
apt-get install vim    # 安装vim
vim influxdb.conf      # 打开配置文件

 在下方添加些选项,完整配置如下:

[meta]
  dir = "/var/lib/influxdb/meta"

[data]
  dir = "/var/lib/influxdb/data"
  engine = "tsm1"
  wal-dir = "/var/lib/influxdb/wal"
#默认是不用用户密码的, 是否开启认证,默认值:false
[http]
  auth-enabled = false
  • 创建管理员账户
root@59d2f87e8efd:/# influx
Connected to http://localhost:8086 version 1.8.10
InfluxDB shell version: 1.8.10
> create user "admin" with password 'admin' with all privileges #创建用户
  •  重启容器,并创建数据库

        先exit退出到宿主机

[root@sz-flum ~]# docker restart influxdb1.8 #重启容器使配置生效
influxdb1.8
[root@sz-flum ~]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS       PORTS                                       NAMES
3e4403f0f068   influxdb:1.8   "/entrypoint.sh infl…"   3 hours ago   Up 3 hours   0.0.0.0:8086->8086/tcp, :::8086->8086/tcp   influxdb1.8

[root@sz-flum ~]# docker restart influxdb1.8
influxdb1.8
[root@sz-flum ~]# docker exec -it 3e bin/bash

root@3e4403f0f068:/# influx
Connected to http://localhost:8086 version 1.8.10
InfluxDB shell version: 1.8.10
> auth     # 主动认证
username: admin
password: 
> create database note # 创建数据库
> show databases
name: databases
name
----
_internal
note
>

整合SpringBoot

  •  添加依赖
<dependency>
            <groupId>com.influxdb</groupId>
            <artifactId>influxdb-client-java</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.influxdb</groupId>
            <artifactId>influxdb-java</artifactId>
            <version>2.14</version>
        </dependency>
  • 新增配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class InfluxdbConfig {
    @Value("${spring.influx.user}")
    public String userName;

    @Value("${spring.influx.password}")
    public String password;

    @Value("${spring.influx.url}")
    public String url;

    //数据库
    @Value("${spring.influx.database}")
    public String database;
}
  • 新增工具类
import com.rz.config.InfluxdbConfig;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
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.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class InfluxDBService {

    @Autowired
    InfluxdbConfig influxDBConfig;

    @PostConstruct
    public void initInfluxDb() {
        this.retentionPolicy = retentionPolicy == null || "".equals(retentionPolicy) ? "autogen" : retentionPolicy;
        this.influxDB = influxDbBuild();
    }
    //保留策略
    private String retentionPolicy;

    private InfluxDB influxDB;

    /**
     * 设置数据保存策略 defalut 策略名 /database 数据库名/ 30d 数据保存时限30天/ 1 副本个数为1/ 结尾DEFAULT
     * 表示 设为默认的策略
     */
    public void createRetentionPolicy() {
        String command = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s REPLICATION %s DEFAULT",
                "defalut", influxDBConfig.database, "30d", 1);
        this.query(command);
    }

    /**
     * 连接时序数据库;获得InfluxDB
     **/
    private InfluxDB influxDbBuild() {
        if (influxDB == null) {
            influxDB = InfluxDBFactory.connect(influxDBConfig.url, influxDBConfig.userName, influxDBConfig.password);
            influxDB.setDatabase(influxDBConfig.database);
        }
        return influxDB;
    }

    /**
     * 插入
     * @param measurement 表
     * @param tags        标签
     * @param fields      字段
     */
    public void insert(String measurement, Map<String, String> tags, Map<String, Object> fields) {
        influxDbBuild();
        Point.Builder builder = Point.measurement(measurement);
        builder.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        builder.tag(tags);
        builder.fields(fields);
        influxDB.write(influxDBConfig.database, "", builder.build());
    }

    /**
     * @desc 插入,带时间time
     * @date 2021/3/27
     *@param measurement
     *@param time
     *@param tags
     *@param fields
     * @return void
     */
    public void insert(String measurement, long time, Map<String, String> tags, Map<String, Object> fields) {
        influxDbBuild();
        Point.Builder builder = Point.measurement(measurement);
        builder.time(time, TimeUnit.MILLISECONDS);
        builder.tag(tags);
        builder.fields(fields);
        influxDB.write(influxDBConfig.database, "", builder.build());
    }

    /**
     * @desc influxDB开启UDP功能,默认端口:8089,默认数据库:udp,没提供代码传数据库功能接口
     * @date 2021/3/13
     *@param measurement
     *@param time
     *@param tags
     *@param fields
     * @return void
     */
    public void insertUDP(String measurement, long time, Map<String, String> tags, Map<String, Object> fields) {
        influxDbBuild();
        Point.Builder builder = Point.measurement(measurement);
        builder.time(time, TimeUnit.MILLISECONDS);
        builder.tag(tags);
        builder.fields(fields);
        int udpPort = 8089;
        influxDB.write(udpPort,  builder.build());
    }

    /**
     * 查询
     * @param command 查询语句
     * @return
     */
    public QueryResult query(String command) {
        influxDbBuild();
        return influxDB.query(new Query(command, influxDBConfig.database));
    }

    /**
     * @desc 查询结果处理
     * @date 2021/5/12
     *@param queryResult
     */
    public List<Map<String, Object>> queryResultProcess(QueryResult queryResult) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<QueryResult.Result> resultList =  queryResult.getResults();
        //把查询出的结果集转换成对应的实体对象,聚合成list
        for(QueryResult.Result query : resultList){
            List<QueryResult.Series> seriesList = query.getSeries();
            if(seriesList != null && seriesList.size() != 0) {
                for(QueryResult.Series series : seriesList){
                    List<String> columns = series.getColumns();
                    String[] keys =  columns.toArray(new String[columns.size()]);
                    List<List<Object>> values = series.getValues();
                    if(values != null && values.size() != 0) {
                        for(List<Object> value : values){
                            Map<String, Object> map = new HashMap(keys.length);
                            for (int i = 0; i < keys.length; i++) {
                                map.put(keys[i], value.get(i));
                            }
                            mapList.add(map);
                        }
                    }
                }
            }
        }
        return mapList;
    }

    /**
     * @desc InfluxDB 查询 count总条数
     * @date 2021/4/8
     */
    public long countResultProcess(QueryResult queryResult) {
        long count = 0;
        List<Map<String, Object>> list = queryResultProcess(queryResult);
        if(list != null && list.size() != 0) {
            Map<String, Object> map = list.get(0);
            double num = (Double)map.get("count");
            count = new Double(num).longValue();
        }
        return count;
    }

    /**
     * 查询
     * @param dbName 创建数据库
     * @return
     */
    public void createDB(String dbName) {
        influxDbBuild();
        influxDB.createDatabase(dbName);
    }

    /**
     * 批量写入测点
     *
     * @param batchPoints
     */
    public void batchInsert(BatchPoints batchPoints) {
        influxDbBuild();
        influxDB.write(batchPoints);
    }

    /**
     * 批量写入数据
     *
     * @param database  数据库
     * @param retentionPolicy 保存策略
     * @param consistency   一致性
     * @param records 要保存的数据(调用BatchPoints.lineProtocol()可得到一条record)
     */
    public void batchInsert(final String database, final String retentionPolicy,
                            final InfluxDB.ConsistencyLevel consistency, final List<String> records) {
        influxDbBuild();
        influxDB.write(database, retentionPolicy, consistency, records);
    }

    /**
     * @desc 批量写入数据
     * @date 2021/3/19
     *@param consistency
     *@param records
     */
    public void batchInsert(final InfluxDB.ConsistencyLevel consistency, final List<String> records) {
        influxDbBuild();
        influxDB.write(influxDBConfig.database, "", consistency, records);
    }

}
  • 测试
private final String measurement = "test"; #表名

    @Autowired
    private InfluxDBServiceImpl influxDBServiceImpl;
    
    public void test(){
        // field
        Map<String, Object> fields = new HashMap<>();
        fields.put("price",480);
        fields.put("type","test");
        fields.put("name","sam");
        // tag
        Map<String, String> tags = new HashMap<>();
        tags.put("price","999");
        influxDBServiceImpl.insert(measurement, tags, fields);
    }