InfluxDB时序数据库

InfluxDB

InfluxDB(时序数据库)是一个由InfluxData开发的开源时序型数据。由Go写成,着力于高性能地查询与存储时序型数据。存储和分析时间序列数据的开源数据库。

常用的使用场景:监控数据统计。每毫秒记录电脑内存的使用情况,然后可以根据统计的数据,利用图形化界面制作内存使用情况的折线图。

特点

  • 为时间序列数据专门编写的自定义高兴你呢数据存储。TSM引擎具有高性能地写入和数据压缩
  • Golang编写,无其他依赖
  • 提供简单、高性能地写入、查询http api
  • 插件支持其他数据写入协议,如 grapgite、collectd、OpenTSDB
  • 支持类sql查询语句
  • tags可以索引序列化,提供快速有效的查询
  • Retention policies自动处理过期数据
  • Continuous queries自动聚合,提高查询效率

安装

RedHat和CentOS用户可以直接用yum包管理来安装最新版本的InfluxDB

cat <<EOF | sudo tee /etc/yum.repos.d/influxdb.repo
[influxdb]
name = InfluxDB Repository - RHEL \$releasever
baseurl = https://repos.influxdata.com/rhel/\$releasever/\$basearch/stable
enabled = 1
gpgcheck = 1
gpgkey = https://repos.influxdata.com/influxdb.key
EOF

一旦加到了yum源里面,就可以运行下面的命令来安装和启动InfluxDB服务:

sudo yum install influxdb
sudo service influxdb start

如果你的系统可以使用Systemd(比如CentOS 7+, RHEL 7+),也可以这样启动:

sudo yum install influxdb
sudo systemctl start influxdb

启动influxdb

systemctl start influxdb
-- 开机自启
systemctl enable influxdb

firewall-cmd --zone=public --list-ports

firewall-cmd --zone=public --add-port=8086/tcp --permanent // 8086为InfluxDB端口

firewall-cmd --reload

测试

[root@localhost /]# influx
Connected to http://localhost:8086 version 1.8.3
InfluxDB shell version: 1.8.3
> show databases
name: databases
name
----
_internal
> quit
[root@localhost /]# 

influxdb可视化工具及使用

参考文章 https://blog.csdn.net/xiaocxyczh/article/details/78969144

influxdb数据库是目前使用最广泛的时序数据库,但很难找到它的可视化管理工具,我最近找到了一款比较简陋的,使用起来还比较方便,步骤如下:

1.新建连接,填写用户名和密码(默认都是root),不要填Database,填了的话只连接到那个数据库

img

2.创建连接后,展开数据库可进行sql操作(只能通过sql语句操作数据)

img

这一部分可以查看一个表的tag、field等字段

下载链接:https://pan.baidu.com/s/1jIjDzDk

基本概念

数据格式

field valuefield keyfield set
tag valuetag keytag set
timestampmeasurementretention policy
seriespointdatabase

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XtL4KGpY-1602837405624)(C:\Users\23990\AppData\Roaming\Typora\typora-user-images\1602141024228.png)]

timestamp:time存着时间戳,这个时间戳以RFC3339格式展示了与特定数据相关联的UTC日期和时间。
field set:每组field key和field value的集合,如butterflies = 3, honeybees = 28
field key/value:在InfluxDB中不能没有field,field没有索引。
tag set:不同的每组tag key和tag value的集合,如location = 1, scientist = langstroth
tag key/value:在InfluxDB中可以没有tag,tag是索引起来的。
measurement: 是一个容器,包含了列time,field和tag。概念上类似表。
retention policy:单个measurement可以有不同的retention policy。measurement默认会有一个autogen的保留策略,autogen中的数据永不删除且备份数replication为1(只有一份数据,在集群中起作用)。
series:series是共同retention policy,measurement和tag set的集合。如下:

任意series编号retention policymeasurementtag set
series 1autogencensuslocation = 1,scientist = langstroth
series 2autogencensuslocation = 2,scientist = langstroth
series 3autogencensuslocation = 1,scientist = perpetua
series 4autogencensuslocation = 2,scientist = perpetua

point:point是具有相同timestamp、相同series(measurement,rp,tag set相同)的field。这个点在此时刻是唯一存在的。 相反,当你使用与该series中现有点相同的timestamp记将新point写入同一series时,该field set将成为旧field set和新field set的并集。

与MySQL的对比

概念MySQLInfluxDB
数据库(同)databasedatabase
表(不同)tablemeasurement
列(不同)columntag(带索引的,非必须)、field(不带索引)、timestemp(唯一主键)
  • tag set:不同的每组tag key和tag value的集合;

  • field set:每组field key和field value的集合;

  • retention policy:数据存储策略(默认策略为autogen)InfluxDB没有删除数据操作,规定数据的保留时间达到清除数据的目的;

  • series:共同retention policy,measurement和tag set的集合;

示例数据如下: 其中census是measurement,butterflies和honeybees是field key,location和scientist是tag key

name: census
————————————
time                 butterflies     honeybees     location     scientist
2015-08-18T00:00:00Z      12             23           1         langstroth
2015-08-18T00:00:00Z      1              30           1         perpetua
2015-08-18T00:06:00Z      11             28           1         langstroth
2015-08-18T00:06:00Z      11             28           2         langstroth

注意点

  • tag 只能为字符串类型
  • field 类型无限制
  • 不支持join
  • 支持连续查询操作(汇总统计数据):CONTINUOUS QUERY
  • 配合Telegraf服务(Telegraf可以监控系统CPU、内存、网络等数据)
  • 配合Grafana服务(数据展现的图像界面,将influxdb中的数据可视化)

常用InfluxQL

-- 进入命令行
influx -precision rfc3339

-- 查看所有的数据库
show databases;

-- 新建数据库
create database test

-- 删除数据库
drop database test

-- 使用特定的数据库
use database_name;


-- 查看所有的measurement(表)
show measurements;

-- 新建表(系统会自带追加时间戳)
insert disk_free,hostname=server01 value=442221834240i
-- 或者添加数据时,自己写入时间戳
insert disk_free,hostname=server01 value=442221834240i 1435362189575692182

-- 删除表
drop measurement disk_free

-- 查询10条数据
select * from measurement_name limit 10;

-- 数据中的时间字段默认显示的是一个纳秒时间戳,改成可读格式
precision rfc3339; -- 之后再查询,时间就是rfc3339标准格式

-- 或可以在连接数据库的时候,直接带该参数
influx -precision rfc3339

-- 查看一个measurement中所有的tag key 
show tag keys

-- 查看一个measurement中所有的field key 
show field keys

-- 查看一个measurement中所有的保存策略(可以有多个,一个标识为default)
show retention policies;

数据保存策略

-- 查看当前数据库保存策略(Retention Policies)
show retention policies on "db_name"

-- 创建新的保存策略(Rete
create retention policy "rp_name" on "db_name" duration 3w replication 1 default

-- rp_name:策略名;
-- db_name:具体的数据库名;
-- 3w:保存3周,3周之前的数据将被删除,influxdb具有各种事件参数,比如:h(小时),d(天),w(星期);
-- replication 1:副本个数,一般为1就可以了;
-- default:设置为默认策略

-- 修改保存策略(Retention Policies)
alter retention policy "rp_name" on "db_name" duration 30d default

-- 删除保存策略(Retention Policies)
drop retention policy "rp_name" on "db_name"

连续查询

-- 显示所有已存在的连续查询(Continuous Queries)
SHOW CONTINUOUS QUERIES

-- 删除连续查询(Continuous Queries)
DROP CONTINUOUS QUERY <cq_name> ON <database_name>

springboot集成influxdb

1、引入依赖

<!-- influxdb-->
<dependency>
    <groupId>org.influxdb</groupId>
    <artifactId>influxdb-java</artifactId>
    <version>2.15</version>
</dependency>

2、yml

spring:
  influx:
    url: http://192.168.128.200:8086
    database: test

3、config

@Configuration
public class InfluxDbConfig {
    @Value("${spring.influx.url:''}")
    private String influxDBUrl;
    @Value("${spring.influx.user:''}")
    private String userName;

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

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

    @Bean
    public InfluxDbUtils influxDbUtils() {
        return new InfluxDbUtils (userName, password, influxDBUrl, database, "logmonitor");
    }
}

4、util

@Data
public class InfluxDbUtils {

    private static final Logger log = LoggerFactory.getLogger(InfluxDbUtils.class);

    private String userName;
    private String password;
    private String url;
    private String database;
    private String retentionPolicy;
    // InfluxDB实例
    private InfluxDB influxDB;

    // 数据保存策略
    public static String policyNamePix = "logRetentionPolicy_";

    public InfluxDbUtils(String userName, String password, String url, String database,
                         String retentionPolicy) {
        this.userName = userName;
        this.password = password;
        this.url = url;
        this.database = database;
        this.retentionPolicy = retentionPolicy == null || "".equals(retentionPolicy) ? "autogen" : retentionPolicy;
        this.influxDB = influxDbBuild();
    }

    /**
     * 连接数据库 ,若不存在则创建
     *
     * @return influxDb实例
     */
    private InfluxDB influxDbBuild() {
        if (influxDB == null) {
            influxDB = InfluxDBFactory.connect(url, userName, password);
        }
        try {
            createDB(database);
            influxDB.setDatabase(database);
        } catch (Exception e) {
            log.error("create influx db failed, error: {}", e.getMessage());
        } finally {
            influxDB.setRetentionPolicy(retentionPolicy);
        }
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return 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", database, "30d", 1);
        this.query(command);
    }

    /**
     *  创建数据库
     * @param database
     */
    public void createDB(String database) {
        influxDB.query(new Query("CREATE DATABASE " + database));
    }

    /**
     * 删除数据库
     * @param dbname
     */
    public void deleteDB(String dbname){
        influxDB.query(new Query("drop DATABASE " + database));
    }


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

    /**
     * 插入
     * @param tags 标签
     * @param fields 字段
     */
    public void insert(Map<String, String> tags, Map<String, Object> fields,String measurement){
        Point.Builder builder = Point.measurement(measurement);
        builder.tag(tags);
        builder.fields(fields);

        influxDB.write(database, "", builder.build());
    }

    /**
     * 删除
     * @param command 删除语句
     * @return 返回错误信息
     */
    public String deletemeasurementdata(String command){
        QueryResult result = influxDB.query(new Query(command, database));
        return result.getError();
    }
}

5、controller

@RestController
public class UserController {
    @Resource
    private UserMapper userMapper;

    @Resource
    private InfluxDbUtils influxDbUtils;

    @GetMapping("/user")
    public List<Username> users(){
        influxDbUtils.createDB("aaa");
        return userMapper.selectList(null);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值