influxdb常用命令、influxdb增删改查、SpringBoot整合influxdb

influxdb常用命令、influxdb增删改查、SpringBoot整合influxdb

  • 一、influxdb一些概念
    • 1、时序数据库
    • 2、influxdb和mysql类比
    • 3、points(类似表的一行数据)数据结构
    • 4、measurement特性
    • 5、Tag和Field
    • 6、Series
  • 二、数据库、表操作命令
  • 三、influxdb的sql操作
    • 1、select
    • 2、where语句
  • 四、SpringBoot整合influxdb
  • 五、influxdb图形化界面客户端

一、influxdb一些概念

Influxdb是一个开源的分布式时序、时间和指标数据库,使用go语言编写,无需外部依赖。 注意:
influxdb只针对单机版开源,集群版还是要收费的。

1、时序数据库

什么是时间序列数据库,最简单的定义就是数据格式里包含Timestamp字段的数据,比如某一时间环境的温度,CPU、内存的使用率等。

influxdb常用来存储一些性能数据,比如cpu使用率,网络的流入、流出速率。根据性能数据就可以监控设备的状态,监控系统中常用influxdb。

2、influxdb和mysql类比

influxdb常用命令、influxdb增删改查、SpringBoot整合influxdb_第1张图片

3、points(类似表的一行数据)数据结构

influxdb常用命令、influxdb增删改查、SpringBoot整合influxdb_第2张图片

4、measurement特性

  • measurement无需单独创建,在第一次插入数据时自动创建。
  • measurement中无数据,表也就不存在了。
  • measurement没有update语句,无法修改measurement以及tags-key和fields-key名称,实际中如有需要只能删除整个measurement重新插入数据。不过也可以通过select * into newxxx from oldxxx,从旧表中查出数据导入到新表。

5、Tag和Field

Tag

  • 相当于mysql的索引
  • Group查询时只能用tag字段

Field

  • 函数操作只能用Field字段,例如sum()
  • 查询时只能使用Field进行比较操作
  • 如果需要使用int,float,boolean类型进行存储,只能使用Field

讲白了,当我们存机器的cpu使用率时,主机的IP,Name等信息用Tag存,而使用率则用Field存。

6、Series

InfluxDB中的series是一种集合的概念,在同一个database中,相同retention policy、相同measurement、相同tag的数据属于一个series集合,同一个series的数据在物理上按照时间顺序排列在一起。

series就是不同tag列,进行排列组合。比如一个表中有两个tag字段A和B。 A字段有有3种值,B字段有4种值,则series个数 = 3*4=12个。

二、数据库、表操作命令

1、数据库操作

//查看所有数据库
show databases
//进入到某个数据库
use influxdb

//查看用户,两列数据,一列是用户名称,一列是是否为管理员用户
show users
//创建普通户
create user "influx" with password '123456'
//创建管理员用户
create user "root" with password '123456' with all privileges
//修改用户密码
set password for root= 'root'
//通过cli操作influxdb
influx -username root -password root
/**
* 数据库设置admin权限的两种方式(建议使用第二种)
*/
GRANT ALL PRIVILEGES ON 数据库名称  TO 用户名称
GRANT ALL PRIVILEGES TO 用户名称
/**
* 数据库撤销admin权限的两种方式(建议使用第二种)
*/
Revoke ALL PRIVILEGES ON 数据库名称 FROM 用户名称
Revoke ALL PRIVILEGES FROM 用户名称

//查看所有表
show measurements
//查看表的tag
show tag keys from 表名称
//查看表的field
show field keys from 表名称
//查看表的series
show series from "表名称"
//查看当前库的series
show series
//查看数据保存策略(建议使用第二种)
show retention policies on "数据库名称"
show retention policies
/**
* 创建数据保留策略
* h(小时),d(天),w(星期)
*/
//CREATE RETENTION POLICY "保留策略名称" ON "数据库名称" DURATION "该保留策略对应的数据过期时间" REPLICATION "复制因子,开源的InfluxDB单机环境永远为1" SHARD DURATION "分片组的默认时长" DEFAULT
create retention policy "testPolice" on myInfluxdb duration 72h    replication 1 SHARD DURATION 1h default
//修改保留策略
alter retention policy "保留策略名称" on "数据库名称" duration 1d
//删除保留策略
drop retention policy "保留策略名称" on "数据库名称"

2、表(插入)操作

一般情况下,经常作为查询条件的列,在初始时设置为tag,即索引,fields不常作为查询条件,更甚者,在复杂查询语法中,聚合语句group by 后面只能是time和tags

/**
* InfluxDB中没有显式的新建表的语句,只能通过insert数据的方式来建立新表。
* 其中 cpu_virtual_used_num就是表名,host,hostname索引(tag),value=xx是记录值(field),记录值可以有多个,后面的时间戳是我们指定的,如果不指定系统自动加当前时间时间戳。
*/
insert cpu_virtual_used_num,host=470b14f0-e869-43ed-a8e6-fd634258271f,hostname=server01 value=0.96516
//删除表
drop measurement cpu_virtual_used_num
//删除数据
//influxDB是没有提供直接删除数据记录的方法,但是提供数据保存策略,主要用于指定数据保留时间,超过指定时间,就删除这部分数据。(数据库过期策略至少一个小时)

三、influxdb的sql操作

1、select

下面是select子句使用的集中几种形式。
influxdb常用命令、influxdb增删改查、SpringBoot整合influxdb_第3张图片

查询注意:

1、如果measurement、tag、field等的标识符除了[A-z,0-9,_]之外,还有其他字符,或者标识符是keyword关键字,那么在引用的时候必须加上双引号。比如在表 h2o_feet 中,"level description"就是一个带有空格的field,如此一来在查询到的时候,就必须加上双引号了。在查询level description时若不加双引号,则会报错。

2、在SELECT 子句中,必须要有至少一个field key!如果在SELECT子句中只有一个或多个tag key,那么该查询会返回空。这是由InfluxDB底层存储数据的方式所导致的结果。

2、where语句

注意事项:
1、在WHERE子句中,支持在fields, tags, and timestamps上进行条件表达式的运算。
2、在InfluxDB的WHERE子句中,不支持使用 OR 来指定不同的time区间,否则将为空。
3、在WHERE子句中,支持对string, boolean, float 和 integer类型的field values进行比较。
4、在WHERE子句中,如果是string类型的field value,一定要用单引号括起来。如果不适用引号括起来,或者使用的是双引号,将不会返回任何数据,有时甚至都不报错!
5、对于在WHERE子句中的tag values,也要用单引号括起来。如果不用引号括起来,或者使用双引号,则查询不会返回任务数据。甚至不会报错。

四、SpringBoot整合influxdb

1、引入maven

 <!-- 引入influxdb-->
 <dependency>
     <groupId>org.influxdb</groupId>
     <artifactId>influxdb-java</artifactId>
 </dependency>

2、application.yml

server:
  port: 8080
spring:
  influx:
    url: http://127.0.0.1:8086 #influxdb服务器的地址
    username:  #用户名
    password:  #密码
    database: rightcloud #指定的数据库
    retention_policy: autogen

3、InfluxdbConfig配置类

import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * influxdb配置文件
 */
@Configuration
public class InfluxdbConfig {

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

    @Value("${spring.influx.username}")
    private String userName;

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

    @Value("${spring.influx.database}")
    private String database;

    @Bean
    public InfluxDB influxdb() {
        InfluxDB influxDB = null;
        if (StringUtils.isEmpty(userName)) {
            influxDB = InfluxDBFactory.connect(influxDBUrl);
        } else {
            influxDB = InfluxDBFactory.connect(influxDBUrl, userName, password);
        }
        try {

            /**
             * 异步插入:
             * enableBatch这里第一个是point的个数,第二个是时间,单位毫秒
             * point的个数和时间是联合使用的,如果满100条或者60 * 1000毫秒
             * 满足任何一个条件就会发送一次写的请求。
             */
//            influxDB.setDatabase(database).enableBatch(100, 1000 * 60, TimeUnit.MILLISECONDS);
            influxDB.setDatabase(database);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //设置默认策略
            this.retention_policy = retention_policy == null || "".equals(retention_policy) ? "autogen" : retention_policy;
            influxDB.setRetentionPolicy(retention_policy);
        }
        //设置日志输出级别
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDB;
    }
}

4、InfluxDBUtils工具类,提供增删改查方法


import org.influxdb.InfluxDB;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Measurement;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Component
public class InfluxDBUtils {

    @Autowired
    private InfluxDB influxDB;

    @Value("${spring.influx.database}")
    private String database;


    /**
     * 插入单条数据写法1
     *
     * @param measurement
     */
    public void insertOne01(String measurement) {
        //构建
        Point.Builder builder = Point.measurement(measurement);
        //可指定时间戳
        builder.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        //tag属性只能存储String类型
        builder.tag("name", "zhanggang");
        //设置field
        builder.addField("filed", "fileValue");
        influxDB.write(builder.build());
    }

    /**
     * 插入单条数据写法2
     *
     * @param measurement
     */
    public void insertOne02(String measurement, Map<String, String> tags, Map<String, Object> fields) {
        //构建
        Point.Builder builder = Point.measurement(measurement);
        //可指定时间戳
        builder.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        //tag属性只能存储String类型
        builder.tag(tags);
        //设置field
        builder.fields(fields);
        influxDB.write(builder.build());
    }

    /**
     * 插入单条数据
     * influxDB开启UDP功能, 默认端口:8089,默认数据库:udp,没提供代码传数据库功能接口
     * 使用UDP的原因
     * TCP数据传输慢,UDP数据传输快。
     * 网络带宽需求较小,而实时性要求高。
     * InfluxDB和服务器在同机房,发生数据丢包的可能性较小,即使真的发生丢包,对整个请求流量的收集影响也较小。
     *
     * @param measurement
     * @param tags
     * @param fields
     */
    public void insertUDPOne03(String measurement, Map<String, String> tags, Map<String, Object> fields) {
        //构建
        Point.Builder builder = Point.measurement(measurement);
        //可指定时间戳
        builder.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        //tag属性只能存储String类型
        builder.tag(tags);
        //设置field
        builder.fields(fields);
        int udpPort = 8089;
        influxDB.write(udpPort, builder.build());
    }


    //批量插入1
    public void insertBatchByRecords() {
        List<String> lines = new ArrayList<String>();
        String measurement = "test-inset-one";
        for (int i = 0; i < 2; i++) {
            Point.Builder builder = Point.measurement(measurement);
            //tag属性只能存储String类型
            builder.tag("name", "zhanggang" + i);
            //设置field
            builder.addField("filed", "fileValue" + i);
            lines.add(builder.build().lineProtocol());
        }
        influxDB.write(lines);
    }


    //批量插入2
    public void insertBatchByPoints() {
        BatchPoints batchPoints = BatchPoints.database(database)
                .consistency(InfluxDB.ConsistencyLevel.ALL)
                .build();
        String measurement = "test-inset-one";
        for (int i = 0; i < 2; i++) {
            Point.Builder builder = Point.measurement(measurement);
            //tag属性只能存储String类型
            builder.tag("name", "zhanggang" + i);
            //设置field
            builder.addField("filed", "fileValue" + i);
            batchPoints.point(builder.build());
        }
        influxDB.write(batchPoints);
    }

    /**
     * 查询,返回Map集合
     *
     * @param query 完整的查询语句
     * @return
     */
    public List<Map<String, Object>> fetchRecords(String query) {
        List<Map<String, Object>> results = new ArrayList<>();
        QueryResult queryResult = influxDB.query(new Query(query, database));
        queryResult.getResults().forEach(result -> {
            result.getSeries().forEach(serial -> {
                List<String> columns = serial.getColumns();
                int fieldSize = columns.size();
                serial.getValues().forEach(value -> {
                    Map<String, Object> obj = new HashMap<String, Object>();
                    for (int i = 0; i < fieldSize; i++) {
                        obj.put(columns.get(i), value.get(i));
                    }
                    results.add(obj);
                });
            });
        });
        return results;
    }

    /**
     * 批量写入数据
     *
     * @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) {
        influxDB.write(database, retentionPolicy, consistency, records);
    }

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

    /**
     * 创建数据保留策略
     * 设置数据保存策略 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", database, "30d", 1);
        this.query(command);
    }
 }

4、在Controller类进行操作


@RestController
public class InfluxDBController {
    @Autowired
    private InfluxDBUtils influxDBUtils;

    @GetMapping("/insertOne")
    public String insertOne() {
        String measurement = "test-inset-one";
        influxDBUtils.insertOne01(measurement);
        return "success";
    }

    @GetMapping("/query01")
    public List<Map<String, Object>> query01() {
        String sql = "SELECT * FROM \"test-inset-one\"   TZ('Asia/Shanghai')";
        return influxDBUtils.fetchRecords(sql);
    }

五、influxdb图形化界面客户端

InfluxDB Studio工具图形化界面操作Influxdb

influxdb常用命令、influxdb增删改查、SpringBoot整合influxdb_第4张图片

InfluxDB Studio:下载链接

你可能感兴趣的:(研究,自创,数据库,database)