InfluxDB环境搭建以及在Springboot中的简单使用

目录

环境搭建

rpm安装

端口

配置文件

启动

查看状态

查看web页面

SHELL命令

链接shell

创建数据库

查看数据库

创建用户

--管理员用户

--创建普通用户并且授权

-- 创建数据库

-- 查询所有表

-- 删除

--写入

--查询具体表数据

-- 清空表数据

JAVA API 使用

yml配置influxdb

Bean方式配置

API调用

官方API

代码详见:

参考资料



环境搭建

rpm安装

wget https://dl.influxdata.com/influxdb/releases/influxdb-1.2.4.x86_64.rpm
yum influxdb-1.2.4.x86_64.rpm

此处安装的是1.2.4,需要注意的是,高版本的不支持web访问。

其他版本的安装可以参考官网,讲解的很详细

https://docs.influxdata.com/influxdb/v1.7/introduction/installation/

端口

  • port 8083:管理页面端口,访问localhost:8083可以进入你本机的influxdb管理页面;
  • port 8086:http连接influxdb client端口,一般使用该端口往本机的influxdb读写数据。

配置文件

/etc/influxdb/influxdb.conf 采用最简单的配置,修改一下2处,分别是设置web访问和http访问的端口、密码

[admin]
  # Determines whether the admin service is enabled.
   enabled = true
  #WEB页面的端口
  # The default bind address used by the admin service.
   bind-address = ":8083"
[http]
  # Determines whether HTTP endpoint is enabled.
  # enabled = true

  # The bind address used by the HTTP service.
  bind-address = ":8086"

  #开启密码
  # Determines whether HTTP authentication is enabled.
  auth-enabled = true

启动

systemctl start influxdb

查看状态

[root@axe1 influxdb]# systemctl status influxdb
● influxdb.service - InfluxDB is an open-source, distributed, time series database
   Loaded: loaded (/usr/lib/systemd/system/influxdb.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2019-10-08 18:54:59 CST; 8min ago
     Docs: https://docs.influxdata.com/influxdb/
 Main PID: 860 (influxd)
   CGroup: /system.slice/influxdb.service
           └─860 /usr/bin/influxd -config /etc/influxdb/influxdb.conf

Oct 08 18:55:00 axe1 influxd[860]: [I] 2019-10-08T10:55:00Z Authentication enabled:true service=httpd
Oct 08 18:55:00 axe1 influxd[860]: [I] 2019-10-08T10:55:00Z Listening on HTTP:[::]:8086 service=httpd
Oct 08 18:55:00 axe1 influxd[860]: [I] 2019-10-08T10:55:00Z Starting retention policy enforcement service with check interval of 30m0s service=retention
Oct 08 18:55:00 axe1 influxd[860]: [I] 2019-10-08T10:55:00Z Listening for signals
Oct 08 18:55:00 axe1 influxd[860]: [I] 2019-10-08T10:55:00Z Storing statistics in database '_internal' retention policy 'monitor', at interval 10s service=monitor
Oct 08 18:55:00 axe1 influxd[860]: [I] 2019-10-08T10:55:00Z Sending usage statistics to usage.influxdata.com
Oct 08 18:55:01 axe1 influxd[860]: [I] 2019-10-08T10:55:01Z beginning level 2 compaction of group 0, 1 TSM files engine=tsm1
Oct 08 18:55:01 axe1 influxd[860]: [I] 2019-10-08T10:55:01Z compacting level 2 group (0) /var/lib/influxdb/data/testdb/autogen/4/000000003-000000002.tsm (#0) engine=tsm1
Oct 08 18:55:01 axe1 influxd[860]: [I] 2019-10-08T10:55:01Z compacted level 2 1 files into 0 files in 2.012775ms engine=tsm1
Oct 08 18:55:20 axe1 influxd[860]: [I] 2019-10-08T10:55:20Z /var/lib/influxdb/data/_internal/monitor/10 database index loaded in 27.72µs service=shard

查看web页面

 

SHELL命令

链接shell

[root@axe1 ~]# influx
Connected to http://localhost:8086 version 1.2.4
InfluxDB shell version: 1.2.4
> auth
username: admin
password:
> show databases
name: databases
name
----
_internal
testdb

>

创建数据库

create database testdb

查看数据库

show databases

创建用户

--管理员用户

   CREATE USER ... 一定要大写,否则会不识别

CREATE USER admin WITH PASSWORD 'admin' WITH ALL PRIVILEGES

--创建普通用户并且授权

CREATE USER test WITH PASSWORD 'test'
GRANT READ ON testdb to test
GRANT WRITE ON testdb to test

使用用户名密码登录
vim /etc/influxdb/influxdb.conf
找到[http] 选项 把auth-enabled设置成true
然后 systemctl restart influxdb 重启

 

此时执行 influx 登录shell客户端
show databases 发现没有权限,于是exit退出
使用influx -username admin -password 'admin'  进行登录后 查询show databases ,正常


-- 创建数据库

使用自定义 Retention Policy
DURATION为数据存储时长,下面的1d即只存1天的数据;
REPLICATION为数据副本,一般在使用集群的时候才会设置为>1;
SHARD DURATION为分区间隔,InfluxDB默认对数据分区,下面的30m即对数据每隔30分钟做一个新的分区;
Name是Retention Policy的名字。

CREATE DATABASE "testdb" WITH DURATION 1d REPLICATION 1 SHARD DURATION 30m NAME "myrp"


-- 可以单独创建Retention Policy,加在已经创建的DB上

CREATE RETENTION POLICY "Alone RP" ON "testdb" DURATION 60m REPLICATION 2 SHARD DURATION 30m

-- 查询所有表

testdb数据库下所有的表(measurements)
 

> use testdb;
Using database testdb
> show measurements;
name: measurements
name
----
flyrecord

-- 删除

testdb数据库下的表flyrecord

> use testdb;
Using database testdb
> drop measurement flyrecord;
> select * from flyrecord ;  //查询不到了
>

--写入

数据
表名(measurements) flyrecord
索引(tag) cpuid的值是edae-fsdw-1111
内容(field) [lat=123.112343] 和 [lon=31.223412]

insert flyrecord,cpuid=edae-fsdw-1111 lat=123.112343,lon=31.223412

说明:insert 之后的第一个字段flyrecord是表名,表名逗号后面的内容是索引的key和value,这里使用的是cpuid=edae-fsdw-1111
然后在索引后面 加上一个空格 就可以写具体的字段内容了,可以是一个 也可以是多个,多个field之前使用逗号隔开。
tag索引也可以是多个,是用逗号隔开

--查询具体表数据

数据

> select * from flyrecord
name: flyrecord
time                cpuid          lat        lon       power value
----                -----          ---        ---       ----- -----
1569756936608570350 edae-fs41-4444                            1
1569756957909065782 edae-fs41-4444                            2
1569756960934153730 edae-fs41-4444                            3
1569757053634546984 edae-fsdw-1111 123.112343 31.223412
1569757550151189402 edae-fsdw-1111 111.112343 12.001234 100
1569757556933183820 edae-fsdw-1111 111.112343 12.001234 99
1569757559758538579 edae-fsdw-1111 111.112343 12.001234 60
> select * from flyrecord ORDER BY time desc LIMIT 2
name: flyrecord
time                cpuid          lat        lon       power value
----                -----          ---        ---       ----- -----
1569757668226541325 222            111.112343 12.001234 60
1569757559758538579 edae-fsdw-1111 111.112343 12.001234 60

-- 清空表数据

> select * from flyrecord
name: flyrecord
time                cpuid cputype lat lon power
----                ----- ------- --- --- -----
1569768669249942553 111   H       1.1 2.2 99

> delete from flyrecord //清空表数据
> select * from flyrecord
>

 

JAVA API 使用

 

新建Springboot工程,引入influxdb的依赖

        
            org.influxdb
            influxdb-java
            2.7
        

同时引入lombok和beanutils和fastjson为后续使用

        
            org.projectlombok
            lombok
            true
        
        
        
            commons-beanutils
            commons-beanutils
            1.9.4
        
        
        
            com.alibaba
            fastjson
            1.2.61
        

yml配置influxdb

application.yml

spring:
  #此处填写配置后,不需要在JAVA代码中再次进行配置,可以直接注入InfluxDB
  influx:
    #端口在/etc/influxdb/influxdb.conf的[http]中配置
    #此处需要[http://]否则会报错【Factory method 'influxDb' threw exception; nested exception is java.lang.IllegalArgumentException: Unable to parse url: 192.168.86.101:8086】
    url: http://192.168.86.101:8086
    user: admin
    password: admin
  application:
    name: influxdb-demo
server:
  port: 18044

Bean方式配置

InfluxDBConfig.java
package com.zzj.influxdbdemo.config;

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.stereotype.Component;

@Component
public class InfluxDBConfig {
    @Value("${spring.influx.user}")
    private String userName;

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

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

    private String database;

    private String retentionPolicy;

    private InfluxDB influxDB;

    public InfluxDBConfig() {
    }


    public InfluxDBConfig(String userName, String password, String url, String database) {
        this.userName = userName;
        this.password = password;
        this.url = url;
        this.database = database;
        build();
    }

    public InfluxDBConfig(String database) {
        this.database = database;
        build();
    }

    private void build(){
        if(influxDB == null){
            influxDB = InfluxDBFactory.connect(this.url,this.userName,this.password);
        }
        influxDB.setDatabase(this.database);
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
    }

    public InfluxDB getInfluxDB() {
        return influxDB;
    }
}

API调用

package com.zzj.influxdbdemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.sun.org.apache.xpath.internal.SourceTree;
import com.zzj.influxdbdemo.config.InfluxDBConfig;
import com.zzj.influxdbdemo.entity.TrackPoint;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/influx")
public class InfluxDBController {

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

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

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


    @Autowired
    private InfluxDB influxDB;

    @GetMapping("/get")
    public String test(){
        String sql = "select * from trackpoint";
        Query query = new Query(sql,"testdb");
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        //毫秒输出
        QueryResult queryResult = influxDB.query(query, TimeUnit.MILLISECONDS);
        List resultList =  queryResult.getResults();

        String sss = queryResult.toString();
        //两种方式都可以
        InfluxDBConfig config = new InfluxDBConfig(userName,password,url,"testdb");
        InfluxDB dbConfig = config.getInfluxDB();
        queryResult = dbConfig.query(query);

        //把查询出的结果集转换成对应的实体对象,聚合成list
        List trackPoints = new ArrayList<>();
        for(QueryResult.Result result:resultList){
            List seriesList = result.getSeries();
            for(QueryResult.Series series : seriesList){
                String name = series.getName();
                Map tags = series.getTags();
                List columns = series.getColumns();
                String[] keys =  columns.toArray(new String[columns.size()]);
                List> values = series.getValues();
                for(List value:values){
                    Map beanMap = new HashMap();
                    TrackPoint point = new TrackPoint();
                    for (int i = 0; i < keys.length; i++) {
                        beanMap.put(keys[i],value.get(i));
                    }
                    try {
                        //查询的时候没用,写入point的时候用
                        Point po = Point.measurement("trackpoint").fields(beanMap).build();
                        //time 默认存入的是UTC格式  2019-09-29T22:58:23.58978834,默认转换成String
                        //{"cpuid":"11","cputype":"H","lat":"10.111222","lon":"78.000111","state":"on","time":"2019-09-29T22:57:06.732701567Z"}
                        BeanUtils.populate(point,beanMap );
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    System.out.println(point.toString());
                    trackPoints.add(point);
                }
            }
        }

        return trackPoints.toString();
    }
    @GetMapping("/insert")
    public void insert(){
        TrackPoint trackPoint = new TrackPoint();
        trackPoint.setCpuid("666");
        trackPoint.setCputype("F");
        trackPoint.setLat(12.335555f);
        trackPoint.setLon(55.125011f);
        trackPoint.setState("on");
        Map bean = new HashMap();
        try {
            //BeanUtils.describe(trackPoint);//这个只能转String,String 不符合要求
            //这个转换也不符合要求,因为转换map过程中,字段类型发生变化,在后面写入influx中,会变成创建新的filed 或者 直接出错。
            //可以自写反射
            String jsonString = JSON.toJSONString(trackPoint);
            bean = JSON.parseObject(jsonString);
            Point po = Point.measurement("trackpoint").fields(bean).build();
            //influxDB.setDatabase("testdb").write(po);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //一种
        Point.Builder builder = Point.measurement("trackpoint");
        builder.time(System.currentTimeMillis(),TimeUnit.MICROSECONDS);
        builder.addField("lat",12.441234f);
        builder.addField("lon",56.512399f);
        builder.addField("state","off");
        builder.tag("cpuid","666888");
        builder.tag("cputype","F");
        Point point = builder.build();
        influxDB.setDatabase("testdb").write(point);
    }
}
 
  

官方API

调用样例

https://github.com/influxdata/influxdb-java

 

代码详见:

https://github.com/MCJIBA/influxdb-demo

 

参考资料

https://www.jianshu.com/p/4e219bc2f1bf

https://www.cnblogs.com/senlinyang/p/8580877.html

https://www.cnblogs.com/morgana/p/8874673.html

https://jasper-zhang1.gitbooks.io/influxdb/content/Introduction/getting_start.html

https://github.com/influxdata/influxdb-java

https://docs.influxdata.com/influxdb/v1.7/introduction/installation/

 

你可能感兴趣的:(InfluxDB)