• influxdb


    InfluxDB概述

    database: 数据库
    measurement:表
    points:记录
    time:每个数据记录时间,是数据库中的主索引,自动生成
    tags: 有索引的字段
    fields:无索引的字段

    命令

    客户端可以使用:InfluxDBStudio-0.2.0

    命令行方式 
    // 客户端连接进infuxdb
    influx -precision rfc3339
    
    // 数据库
    // CREATE DATABASE park_device
    // SHOW DATABASES
    // USE mydb
    // drop database lzhtest
    
    // 表
    // 展示所有表
    show measurements
    // 创建表并插入第一条数据,lzhtest表名,tag是host,region,数据是value,字段的数据类型在第一次插入数据的时候,由数据的数据类型决定的
    insert lzhtest,name=YiHui,phone=110 user_id=20,email="bangzewu@126.com"
    insert lzhtest,name=lzh,phone=111 user_id=20,email="bangzewu@126.com"
    insert measurement+"," + tag=value,tag=value + 空格 + field=value,field=value
    insert device_property,category_id=123,category_no=abc,device_id=1,device_sn=a property_id="temperature",property_value="30",space_code= "001002003"
    时间戳指定,当写入数据不指定时间时,会自动用当前时间来补齐,如果需要自己指定时间时,再最后面添加上即可,注意时间为ns
    insert add_test,name=YiHui,phone=110 user_id=22,email="bangzewu@126.com",age=18i,boy=true 1564150279123000000
    如果要在表中新增tag字段或数据字段,insert的时候加上就行
    tag 可以为空,tag和filed的区别,tag是有索引的属性,field没有索引的属性
    
    // 查表字段信息
    show field keys  from rtvalue
    // 表字段不支持删除
    
    // 查询数据
    SELECT "host", "region", "value" FROM lzhtest
    // 模糊查询
    likeRight: select * from device_property where space_code=~/^001/
    like: select * from device_property where space_code=~/001002/
    likeLeft: select * from device_property where space_code=~/004$/
    
    // 删除数据
    influxDB是没有提供直接删除数据记录的方法,但是提供数据保存策略,主要用于指定数据保留时间,超过指定时间,就删除这部分数据。
    // 删除表
    drop measurement lzhtest
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    统计数据补值

    需求:统计温感探测器,过去24小时的温度变化趋势,时间间隔1小时。
    问题,如果今日0-8小时,温感探测器都没有值,在8小时之后才有值,那么需要拿今日0点之前的数据补值到0-8小时。
    解决方法:

    -- 表示查询某个时间段数据,并且按照time 1分钟分组,last表示取一分钟分组里最新的一条数据,fill表示缺失的数据通过拿前一个数据的值填充
    SELECT LAST("value") FROM rtvalue WHERE time > '2022-10-10T05:40:24.893764015Z' AND time <= '2022-10-10T05:55:24.893764015Z' GROUP BY time(1m) fill(previous)
    -- 取开始时间之前的并且是最后的一条数据。如果上面那条sql, 前面的时间段缺失数据,可以通过这条sql进行补值
    SELECT LAST("value") FROM rtvalue WHERE time <= '2022-10-10T05:40:00Z'
    
    GROUP BY time() 查询会将查询结果按照用户指定的时间区间来进行分组。s秒,m分钟,h小时, d天
    last函数获取最新值(如果该列在最后一条记录中为空,则last()返回具有非空值的前一条记录)
    fill()用于填充没有数据的时序序列的值,其选项为:
    	null: 默认,显示时间戳但value=null的序列;
    	none:在结果中不显示该时间戳的序列;
    	数值:fill(0),填充0;
    	linear: 线性插入数值;前后时序的平均值
    	previous: 填充前一个序列的值;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    spring boot整合influxdb

            
            
                org.influxdb
                influxdb-java
                
                    
                        com.squareup.okhttp3
                        *
                    
                
            
            
            
                com.squareup.okhttp3
                okhttp
                4.0.0
            
            
                com.squareup.okhttp3
                logging-interceptor
                4.0.0
                
                    
                        okhttp
                        com.squareup.okhttp3
                    
                
            
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    配置类:

    @Configuration
    public class InfluxDBConfig {
        @Value("${spring.influx.user:xxx}")
        private String userName;
    
        @Value("${spring.influx.password:xxx}")
        private String password;
    
        @Value("${spring.influx.url:http://ip:port}")
        private String url;
    
        //数据库
        @Value("${spring.influx.database:park_device}")
        private String database;
    
        @Bean
        public InfluxDB influxDB() {
            InfluxDB influxDB = InfluxDBFactory.connect(url, userName, password);
             if (!influxDB.databaseExists(database)) {
                 influxDB.createDatabase(database);
             }
            influxDB.setDatabase(database);
            return influxDB;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    基本的增删改查:

    public interface TSDBService {
        void insert(Object object);
        void insert(String measurement, Map tags, Map fields);
        void batchInsert(List batchPointAOS);
         List query(String sql, Class clazz);
        QueryResult query(String sql);
    }
    
    @Service
    @Slf4j
    public class BbuInflux implements TSDBService {
        @Autowired
        private InfluxDB influxDB;
    
        @Value("${spring.influx.database:park_device}")
        private String dbName;
    
        /**
         * 添加数据
         * 批量插入,时间相同后面的会覆盖前面的; 每条记录的time不一样或tag不一样就行
         * @param object
         */
        @Override
        public void insert(Object object) {
            Point.Builder pointBuilder = Point.measurementByPOJO(object.getClass());
    
            // 将对象中的所有属性转换为tag添加到point中
            Point point = pointBuilder.addFieldsFromPOJO(object)
                    // 调用time方法设置当前时间,InfluxDB自动生成的time时间列为UTC时间,所以在存储时单独设置
                    .time(LocalDateTime.now().plusHours(8).toInstant(ZoneOffset.of("+8")).toEpochMilli(), TimeUnit.MILLISECONDS)
                    .build();
    
            // 设置要存储的数据库名称
            influxDB.setDatabase(dbName);
            // 将数据插入到表(Measurement)中
            influxDB.write(point);
            influxDB.close();
        }
    
        /**
         * 插入
         * @param measurement 表
         * @param tags        标签
         * @param fields      字段
         */
        @Override
        public void insert(String measurement, Map tags, Map fields) {
            Point.Builder builder = Point.measurement(measurement);
            builder.time(LocalDateTime.now().plusHours(8).toInstant(ZoneOffset.of("+8")).toEpochMilli(), TimeUnit.MILLISECONDS);
            builder.tag(tags);
            builder.fields(fields);
            influxDB.write(dbName, "", builder.build());
            influxDB.close();
        }
    
        /**
         * 批量插入
         * @param batchPointAOS
         */
        @Override
        public void batchInsert(List batchPointAOS) {
            List> split = CollectionUtil.split(batchPointAOS, 300);
            for (List pointAOS : split) {
                BatchPoints batchPoints = BatchPoints.database(dbName).build();
                pointAOS.forEach(batchPointAO->{
                    Point.Builder builder = Point.measurement(batchPointAO.getMeasurement());
                    builder.time(batchPointAO.getTime().plusHours(8).toInstant(ZoneOffset.of("+8")).toEpochMilli(), TimeUnit.MILLISECONDS);
                    builder.tag(batchPointAO.getTags());
                    builder.fields(batchPointAO.getFields());
                    batchPoints.point(builder.build());
                });
                try {
                    influxDB.write(batchPoints);
                } catch (Exception e) {
                    log.error("save data to influxdb fail : {}", e.getMessage());
                }
            }
            influxDB.close();
        }
    
    
    
        /**
         * 通用查询封装
         *
         * @param sql
         * @param clazz
         * @param
         * @return
         */
        @Override
        public  List query(String sql, Class clazz) {
            QueryResult queryResult = influxDB.query(new Query(sql, dbName));
            influxDB.close();
            InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
            return resultMapper.toPOJO(queryResult, clazz);
        }
    
        @Override
        public QueryResult query(String sql) {
            return influxDB.query(new Query(sql, dbName));
        }
    }
    
    /**
     * @Description TODO
     * @date 2022/10/13 16:00
     * @Author liuzhihui
     * @Version 1.0
     */
    @Slf4j
    public class InfluxUtil {
        /**
         * @desc 查询结果处理
         * @date 2021/5/12
         *@param queryResult
         */
        public static List> queryResultProcess(QueryResult queryResult) {
            List> mapList = new ArrayList<>();
            List resultList =  queryResult.getResults();
            //把查询出的结果集转换成对应的实体对象,聚合成list
            for(QueryResult.Result query : resultList){
                List seriesList = query.getSeries();
                if(seriesList != null && seriesList.size() != 0) {
                    for(QueryResult.Series series : seriesList){
                        List columns = series.getColumns();
                        String[] keys =  columns.toArray(new String[columns.size()]);
                        List> values = series.getValues();
                        if(values != null && values.size() != 0) {
                            for(List value : values){
                                Map 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;
        }
    
        /**
         * influxdb的time使用的UTC时间格式,相比北京时间会有8小时的差距, 所以在做时间范围查询时做特殊处理
         * 获取UTC时间,并减少8小时
         * @param timeStr
         * @return
         */
        public static String getUTC (String timeStr){
            DateFormat dtfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                Date date1 = simpleDateFormat.parse(timeStr);
                Calendar ca = Calendar.getInstance();
                ca.setTime(date1);
                //日期减8小时,新增的时候+过8小时,这里就不用减了
    //            ca.add(Calendar.HOUR,-8);
                Date dt1=ca.getTime();
                String reslut = dtfUTC.format(dt1);
                return reslut;
            }catch (ParseException e) {
                log.info("获取UTC时间,并减少8小时异常");
                log.error(e.getMessage(), e);
            }
            return timeStr;
        }
        
        /**
         * 格式化utc时间
         * @param utcTime
         * @return
         */
        public static String parseUTC(String utcTime){
            LocalDateTime dateTime = LocalDateTime.parse(utcTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formatTime = df.format(dateTime);
            return formatTime;
        }
    }
    
    @Data
    public class BatchPointAO {
        String measurement;
        Map tags;
        Map fields;
        LocalDateTime time = LocalDateTime.now();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189

    参考
    官方文档:https://docs.influxdata.com/influxdb/v1.7/introduction/getting-started/
    InfluxDB 常用命令:https://blog.csdn.net/qq_42761569/article/details/110443500
    InfluxDB基本命令:https://blog.csdn.net/qq_32014795/article/details/116518364
    https://www.cnblogs.com/gaoguangjun/p/8513021.html
    springboot整合:https://blog.csdn.net/lizhengyu891231/article/details/123869635
    spring整合原生:https://blog.csdn.net/qq_38628046/article/details/122495583
    https://blog.csdn.net/yinjl123456/article/details/117562452

    时间序列数据库 TSDB 概念入门: https://help.aliyun.com/document_detail/55709.html
    https://db-engines.com/de/ranking/time+series+dbms

  • 相关阅读:
    【PyTorch深度学习项目实战100例】—— 基于DenseNet121实现26个英文字母识别任务 | 第41例
    接口中如何优雅的接收时间类型参数
    智能中仍存在着许多未被发现的逻辑
    centos 7安装podman(类似docker)
    DGIOT国内首家轻量级物联网开源平台——MQTT接入实战教程
    shopee店铺销量突然下降怎么办——扬帆志远
    [C/C++]数据结构 链表OJ题:移除链表元素
    程序员买啥游戏机,自己动手做一个体感小游戏
    cocos 3.x 2D角色键盘移动
    docker的再定义镜像和上传阿里云
  • 原文地址:https://blog.csdn.net/weixin_42412601/article/details/127431019