springboot接入influxdb
转载请注明出处:
1.添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.influxdb</groupId>
<artifactId>influxdb-java</artifactId>
<version>2.14</version>
</dependency>
2.spring boot 的application.yaml配置文件中添加influxdb的配置
influxdb:
url: http://127.0.0.1:8086
database: influx_db
username: influx_db_user
password: influx_db_pwd
8086 为influxdb默认的端口
3.influxdb配置应用与service方法编写
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
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.Value;
import org.springframework.stereotype.Service; import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; @Service
public class InfluxDBService { @Value("${influxdb.username}")
public String influxdbUserName; @Value("${influxdb.password}")
public String influxdbPassword; @Value("${influxdb.url}")
public String influxdbUrl; //数据库
@Value("${influxdb.database}")
public String influxdbDatabase; @PostConstruct
public void initInfluxDb() {
this.retentionPolicy = retentionPolicy == null || "".equals(retentionPolicy) ? "autogen" : retentionPolicy;
this.influxDB = influxDbBuild();
}
//保留策略
private String retentionPolicy; private InfluxDB 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", influxdbDatabase, "30d", 1);
this.query(command);
} /**
* 连接时序数据库;获得InfluxDB
**/
private InfluxDB influxDbBuild() {
if (influxDB == null) {
influxDB = InfluxDBFactory.connect(influxdbUrl, influxdbUserName, influxdbPassword);
influxDB.setDatabase(influxdbDatabase);
}
return influxDB;
} /**
* 插入
* @param measurement 表
* @param tags 标签
* @param fields 字段
*/
public void insert(String measurement, Map<String, String> tags, Map<String, Object> fields) {
influxDbBuild();
Point.Builder builder = Point.measurement(measurement);
builder.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
builder.tag(tags);
builder.fields(fields);
influxDB.write(influxdbDatabase, "", builder.build());
} /**
* @desc 插入,带时间time
* @date 2021/3/27
*@param measurement
*@param time
*@param tags
*@param fields
* @return void
*/
public void insert(String measurement, long time, Map<String, String> tags, Map<String, Object> fields) {
influxDbBuild();
Point.Builder builder = Point.measurement(measurement);
builder.time(time, TimeUnit.MILLISECONDS);
builder.tag(tags);
builder.fields(fields);
influxDB.write(influxdbDatabase, "", builder.build());
} /**
* @desc influxDB开启UDP功能,默认端口:8089,默认数据库:udp,没提供代码传数据库功能接口
* @date 2021/3/13
*@param measurement
*@param time
*@param tags
*@param fields
* @return void
*/
public void insertUDP(String measurement, long time, Map<String, String> tags, Map<String, Object> fields) {
influxDbBuild();
Point.Builder builder = Point.measurement(measurement);
builder.time(time, TimeUnit.MILLISECONDS);
builder.tag(tags);
builder.fields(fields);
int udpPort = 8089;
influxDB.write(udpPort, builder.build());
} /**
* 查询
* @param command 查询语句
* @return
*/
public QueryResult query(String command) {
influxDbBuild();
return influxDB.query(new Query(command, influxdbDatabase));
} /**
* @desc 查询结果处理
* @date 2021/5/12
*@param queryResult
*/
public List<Map<String, Object>> queryResultProcess(QueryResult queryResult) {
List<Map<String, Object>> mapList = new ArrayList<>();
List<QueryResult.Result> resultList = queryResult.getResults();
//把查询出的结果集转换成对应的实体对象,聚合成list
for(QueryResult.Result query : resultList){
List<QueryResult.Series> seriesList = query.getSeries();
if(seriesList != null && seriesList.size() != 0) {
for(QueryResult.Series series : seriesList){
List<String> columns = series.getColumns();
String[] keys = columns.toArray(new String[columns.size()]);
List<List<Object>> values = series.getValues();
if(values != null && values.size() != 0) {
for(List<Object> value : values){
Map<String, Object> 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;
} /**
* @desc InfluxDB 查询 count总条数
* @date 2021/4/8
*/
public long countResultProcess(QueryResult queryResult) {
long count = 0;
List<Map<String, Object>> list = queryResultProcess(queryResult);
if(list != null && list.size() != 0) {
Map<String, Object> map = list.get(0);
double num = (Double)map.get("count");
count = new Double(num).longValue();
}
return count;
} /**
* 查询
* @param dbName 创建数据库
* @return
*/
public void createDB(String dbName) {
influxDbBuild();
influxDB.createDatabase(dbName);
} /**
* 批量写入测点
*
* @param batchPoints
*/
public void batchInsert(BatchPoints batchPoints) {
influxDbBuild();
influxDB.write(batchPoints);
} /**
* 批量写入数据
*
* @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) {
influxDbBuild();
influxDB.write(database, retentionPolicy, consistency, records);
} /**
* @desc 批量写入数据
* @date 2021/3/19
*@param consistency
*@param records
*/
public void batchInsert(final InfluxDB.ConsistencyLevel consistency, final List<String> records) {
influxDbBuild();
influxDB.write(influxdbDatabase, "", consistency, records);
} }
4.进行单元测试验证
@SpringBootTest
public class InfluxDbTest { @Autowired
private InfluxDBService influxDBService; @Test
void contextLoads() {
} @Test
public void testSave(){
String measurement = "host_cpu_usage_total"; Map<String,String> tags = new HashMap<>();
tags.put("host_name","host2");
tags.put("cpu_core","core0"); Map<String, Object> fields = new HashMap<>();
fields.put("cpu_usage",0.22);
fields.put("cpu_idle",0.56);
influxDBService.insert(measurement, tags, fields);
}
}
influxdb 在执行新增测试用例的时候,如果influxdb的数据库中对应的表不存在,会自动创建数据库表
5.查询示例

springboot接入influxdb的更多相关文章
- Springboot接入ChatGPT 续
在之前的文章\(^{[ 1 ]}\)中,原方案的设计,是基于功能实现的角度去设计的,对于功能性的拓展,考虑不全面,结合收到的反馈意见,对项目进行了拓展优化.完成的优化拓展有如下几个方面 固定会话 历史 ...
- SpringBoot接入轻量级分布式日志框架(GrayLog)
我是3y,一年CRUD经验用十年的markdown程序员常年被誉为优质八股文选手 前两天我不是发了一篇数据链路追踪的文章嘛,在末尾也遗留了TODO:运行应用的服务器一般是集群,日志数据会记录到不同的 ...
- springboot 接入 ChatGPT
项目地址 https://gitee.com/Kindear/lucy-chat 介绍 lucy-chat是接入OpenAI-ChatGPT大模型人工智能的Java解决方案,大模型人工智能的发展是不可 ...
- SpringBoot接入微信JSSDK,看这篇妥妥的
先给猴急的客官上干货代码 GitHub 接入微信JSSDK GitHub地址 Gitee 接入微信JSSDK GitHub地址 前言 事情的起因是因为疫情严重,领导要求做一个专题页,能够尽可能帮助所需 ...
- Springboot接入RabbitMQ详细教程
本文适用于对 RabbitMQ 有所了解的人,在此不讨论MQ的原理,只讨论如何接入.其实Spring Boot 集成 RabbitMQ 非常简单,本文章使用的是Spring Boot 提供了sprin ...
- SpringBoot接入两套kafka集群
引入依赖 compile 'org.springframework.kafka:spring-kafka' 第一套kafka配置 package myapp.kafka; import lombok. ...
- Spring-boot之 rabbitmq
今天学习了下spring-boot接入rabbitmq. windows下的安装:https://www.cnblogs.com/ericli-ericli/p/5902270.html 使用博客:h ...
- 很详细的SpringBoot整合UEditor教程
很详细的SpringBoot整合UEditor教程 2017年04月10日 20:27:21 小宝2333 阅读数:21529 版权声明:本文为博主原创文章,未经博主允许不得转载. https: ...
- 5 springboot 集成dubbo
Apache Dubbo 是一款高性能Java RPC框架 由阿里巴巴开源并进入Apache孵化器,官网 http://dubbo.apache.org 提供服务化基础功能: 接口远程调用,智能负载均 ...
- springboot整合swagger。完爆前后端调试
web接口开发时在调试阶段最麻烦的就是参数调试,前端需要咨询后端.后端有时候自己也不是很了解.这时候就会造成调试一次接口就需要看一次代码.Swagger帮我们解决对接的麻烦 springboot接入s ...
随机推荐
- 你需要知道的 14 个常用的 JavaScript 函数
1.确定任意对象的具体类型 众所周知,JavaScript 中有六种原始数据类型(Boolean.Number.String.Null.Undefined.Symbol)和一个对象数据类型.但是你知道 ...
- JS有哪些变态语法,你知道吗?
JS作为一门如此灵活的语言,自然在编码时给我们带来了很多方便,但方便的同时,也衍生出了很多变态的语法,下面我们来梳理一些常见的变态语法,希望你下次在某位大牛的代码中看到这样的东西,不要惊掉下巴. NO ...
- STL常用容器用法总结
vector 变长数组,倍增的思想 size() 返回元素个数 empty() 返回是否为空 clear() 清空 front()/back() push_back()/pop_back() begi ...
- 在windows系统中设置MySQL数据库
MySQL搭建 效果图 step1:下载安装包 https://downloads.mysql.com/archives/community/ step2:解压后即完成安装 step3:创建 my.i ...
- Synchronized和Volatile的对比
Synchronized和Volatile是并发中的两大关键字,有相似性和不同点. Synchronized更详细介绍参考https://www.cnblogs.com/spark-cc/p/1706 ...
- Little Snitch 5 - Mac 老牌防火墙安全工具软件小飞贼,监控和组织特定软件的网络连接
一旦连接到Internet,应用程序就可以随时随地发送它们想要的任何东西.通常情况下,他们是为你做的.但有时,例如在跟踪软件.木马或其他恶意软件的情况下,它们不会.但你不会注意到任何东西,因为所有这些 ...
- 有了HTTP,为啥还要用RPC
既然有 HTTP 请求,为什么还要用 RPC 调用? 一直以来都没有深究过RPC和HTTP的区别,不都是写一个服务然后在客户端调用么? HTTP和RPC最本质的区别,就是 RPC 主要是基于 TCP/ ...
- 基于el-cascader级联选择器实现只有最后一级可以多选(已发布到npm & github)
github地址:地址 背景: 我们经常级联合选择器多选的需求,但是element UI提供的级联选择器并不能只多选最后一级,所以我考虑基于element UI的级联选择器优化一下,实现可以多选最后一 ...
- mongodb导入数据,保创建新项目
1.回顾 2.导入数据 2.1 excel数据表格 2.2 设计导入数据的路由 routes/users.js router.get('/upload', function (req, res, ne ...
- Python的函数和方法如何区分呢?
结论>>>:无论是函数还是方法都用def关键字来定义 方法:只要是自动传值都是方法.由谁来调用.会把自身传入 函数:有几个值就传几个值否则会报错 目录 一.详细介绍函数和方法 二.用 ...