InfluxDB工具类

 package com.influxdb.test;

 import java.util.Map;

 import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Point.Builder;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.util.StringUtils; /**
* 时序数据库 InfluxDB 连接
* @author Dai_LW
*
*/
public class InfluxDBConnect { private String username;//用户名
private String password;//密码
private String openurl;//连接地址
private String database;//数据库 private InfluxDB influxDB; public InfluxDBConnect(String username, String password, String openurl, String database){
this.username = username;
this.password = password;
this.openurl = openurl;
this.database = database;
} /**连接时序数据库;获得InfluxDB**/
public InfluxDB influxDbBuild(){
if(influxDB == null){
influxDB = InfluxDBFactory.connect(openurl, username, password);
influxDB.createDatabase(database); }
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 command 查询语句
* @return
*/
public QueryResult query(String command){
return influxDB.query(new Query(command, database));
} /**
* 插入
* @param measurement 表
* @param tags 标签
* @param fields 字段
*/
public void insert(String measurement, Map<String, String> tags, Map<String, Object> fields){
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();
} /**
* 创建数据库
* @param dbName
*/
public void createDB(String dbName){
influxDB.createDatabase(dbName);
} /**
* 删除数据库
* @param dbName
*/
public void deleteDB(String dbName){
influxDB.deleteDatabase(dbName);
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getOpenurl() {
return openurl;
} public void setOpenurl(String openurl) {
this.openurl = openurl;
} public void setDatabase(String database) {
this.database = database;
}
}

测试类

 package com.influxdb.test;

 import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import junit.framework.Assert; import org.influxdb.dto.QueryResult;
import org.influxdb.dto.QueryResult.Result;
import org.influxdb.dto.QueryResult.Series;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.BeanWrapperImpl; import com.influxdb.pojo.CodeInfo; public class InfluxDBTest { private InfluxDBConnect influxDB;
private String username = "admin";//用户名
private String password = "admin";//密码
private String openurl = "http://127.0.0.1:8086";//连接地址
private String database = "test_db";//数据库
private String measurement = "sys_code"; @Before
public void setUp(){
//创建 连接
influxDB = new InfluxDBConnect(username, password, openurl, database); influxDB.influxDbBuild(); influxDB.createRetentionPolicy(); // influxDB.deleteDB(database);
// influxDB.createDB(database);
} @Test
public void testInsert(){//测试数据插入
Map<String, String> tags = new HashMap<String, String>();
Map<String, Object> fields = new HashMap<String, Object>();
List<CodeInfo> list = new ArrayList<CodeInfo>(); CodeInfo info1 = new CodeInfo();
info1.setId(1L);
info1.setName("BANKS");
info1.setCode("ABC");
info1.setDescr("中国农业银行");
info1.setDescrE("ABC");
info1.setCreatedBy("system");
info1.setCreatedAt(new Date().getTime()); CodeInfo info2 = new CodeInfo();
info2.setId(2L);
info2.setName("BANKS");
info2.setCode("CCB");
info2.setDescr("中国建设银行");
info2.setDescrE("CCB");
info2.setCreatedBy("system");
info2.setCreatedAt(new Date().getTime()); list.add(info1);
list.add(info2); for(CodeInfo info : list){ tags.put("TAG_CODE", info.getCode());
tags.put("TAG_NAME", info.getName()); fields.put("ID", info.getId());
fields.put("NAME", info.getName());
fields.put("CODE", info.getCode());
fields.put("DESCR", info.getDescr());
fields.put("DESCR_E", info.getDescrE());
fields.put("CREATED_BY", info.getCreatedBy());
fields.put("CREATED_AT", info.getCreatedAt()); influxDB.insert(measurement, tags, fields);
}
} @Test
public void testQuery(){//测试数据查询
String command = "select * from sys_code";
QueryResult results = influxDB.query(command); if(results.getResults() == null){
return;
}
List<CodeInfo> lists = new ArrayList<CodeInfo>();
for (Result result : results.getResults()) { List<Series> series= result.getSeries();
for (Series serie : series) {
// Map<String, String> tags = serie.getTags();
List<List<Object>> values = serie.getValues();
List<String> columns = serie.getColumns(); lists.addAll(getQueryData(columns, values));
}
} Assert.assertTrue((!lists.isEmpty()));
Assert.assertEquals(2, lists.size());
} @Test
public void testQueryWhere(){//tag 列名 区分大小写
String command = "select * from sys_code where TAG_CODE='ABC'";
QueryResult results = influxDB.query(command); if(results.getResults() == null){
return;
}
List<CodeInfo> lists = new ArrayList<CodeInfo>();
for (Result result : results.getResults()) { List<Series> series= result.getSeries();
for (Series serie : series) {
List<List<Object>> values = serie.getValues();
List<String> columns = serie.getColumns(); lists.addAll(getQueryData(columns, values));
}
} Assert.assertTrue((!lists.isEmpty()));
Assert.assertEquals(1, lists.size()); CodeInfo info = lists.get(0); Assert.assertEquals(info.getCode(), "ABC"); } @Test
public void deletMeasurementData(){
String command = "delete from sys_code where TAG_CODE='ABC'";
String err = influxDB.deleteMeasurementData(command);
Assert.assertNull(err);
} /***整理列名、行数据***/
private List<CodeInfo> getQueryData(List<String> columns, List<List<Object>> values){
List<CodeInfo> lists = new ArrayList<CodeInfo>(); for (List<Object> list : values) {
CodeInfo info = new CodeInfo();
BeanWrapperImpl bean = new BeanWrapperImpl(info);
for(int i=0; i< list.size(); i++){ String propertyName = setColumns(columns.get(i));//字段名
Object value = list.get(i);//相应字段值
bean.setPropertyValue(propertyName, value);
} lists.add(info);
} return lists;
} /***转义字段***/
private String setColumns(String column){
String[] cols = column.split("_");
StringBuffer sb = new StringBuffer();
for(int i=0; i< cols.length; i++){
String col = cols[i].toLowerCase();
if(i != 0){
String start = col.substring(0, 1).toUpperCase();
String end = col.substring(1).toLowerCase();
col = start + end;
}
sb.append(col);
}
return sb.toString();
}
}

Java版InfluxDB工具类的更多相关文章

  1. java版RSA工具类

    /** * RSA算法加密/解密工具类 */ public class RSAUtils { private static final Logger LOGGER = LoggerFactory.ge ...

  2. 170405、java版MD5工具类

    package com.rick.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmExce ...

  3. java influx DB工具类

    配置 application-properties: spring.influxdb.url=${influxdb_host:127.0.0.1} spring.influxdb.port=${inf ...

  4. HttpTool.java(在java tool util工具类中已存在) 暂保留

    HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...

  5. java文件处理工具类

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...

  6. java格式处理工具类

    import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOExceptio ...

  7. Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类

    Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类   =========================== ©Copyright 蕃薯耀 2017年9月25日 http://www ...

  8. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  9. 使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间。

    1.使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间. package com.fline.aic.utils; import java.text.DateFormat ...

随机推荐

  1. 'cordova' 不是内部或外部命令,也不是可运行的程序

    问题: CMD   'cordova'  不是内部或外部命令,也不是可运行的程序: 解决:配置环境变量 1.找到npm的安装路径 :如C:\Users\AppData\Roaming\npm 2.环境 ...

  2. Java的常量和变量

    一.标识符 如类名,数字不能作为标识符的首字母(以字母或者下划线或者$开头且不能有空格) 注意和Python的区别,Python中标识符由字母.下划线和数字组成,且数字不能开头,也是严格区分大小写(但 ...

  3. Python基础:语法基础(3)

    本篇主要介绍Python中一些基础语法,其中包括:标识符.关键字.常量.变量.表达式.语句.注释.模块和包等内容. 1. 标识符和关键字 1.1 标识符 标识符是变量.常量.函数.属性.类.模块和包等 ...

  4. 加载hive-jdbc driver时报错:java.lang.NoClassDefFoundError: org/apache/hadoop/conf/Configuration

    这是因为缺少一个hadoop-common包,引入即可: <dependency> <groupId>org.apache.hadoop</groupId> < ...

  5. django xadmin(1)

    filter_horizontal 从‘多选框’的形式改变为‘过滤器’的方式,水平排列过滤器,必须是一个 ManyToManyField类型,且不能用于 ForeignKey字段,默认地,管理工具使用 ...

  6. 函数中的this与argument对象,以及argument中的callee与caller属性

    相关阅读:https://segmentfault.com/a/1190000015438195 相关阅读: https://zhuanlan.zhihu.com/p/23804247 相关阅读: h ...

  7. jq的on click 事件在苹果下无效

    据说苹果对于点击的对象,拥有cursor:pointer这个样式的设置才算 参考地址:https://blog.csdn.net/yuexiage1/article/details/51612496

  8. NOI2019十二省联考旅游记

    真的是去旅游的啊,毕竟菜是原罪嘛 Day 0 去指定地点试机,果然,键盘还是一如既往的不好用,我也不知道为什么. 晚上,教练请吃自助餐,幸福的像个胖子 Day 1 早上坐车过去,在车上看了看原来写过的 ...

  9. content-type 组件

    content-type初识 什么是content-type ContentType是Django的内置的一个应用,可以追踪项目中所有的APP和model的对应关系,并记录在ContentType表中 ...

  10. DirectX11 With Windows SDK--00 目录

    前言 (更新于 2019/4/10) 从第一次接触DirectX 11到现在已经有将近两年的时间了.还记得前年暑假被要求学习DirectX 11,在用龙书的源码配置项目运行环境的时候都花了好几天的时间 ...