From e5def9fb33dad6b8568de5bc7266d937667a21b6 Mon Sep 17 00:00:00 2001 From: caixiang <939387484@qq.com> Date: Mon, 4 Jul 2022 08:32:21 +0800 Subject: [PATCH] mark --- pom.xml | 17 ++ .../com/cnbm/admin/config/SecurityConfig.java | 1 + ym-gateway/pom.xml | 20 ++ .../java/com/cnbm/config/SwaggerConfig.java | 16 ++ .../src/main/resources/application-dev.yml | 16 +- ym-gateway/src/main/resources/application.yml | 3 +- ym-influx/pom.xml | 76 +++++++ ym-influx/src/main/java/Main2.java | 54 +++++ .../src/main/java/com/cnbm/influx/Main.java | 214 ++++++++++++++++++ .../java/com/cnbm/influx/common/Utils.java | 69 ++++++ .../com/cnbm/influx/config/InfluxClient.java | 133 +++++++++++ .../com/cnbm/influx/constant/Constant.java | 23 ++ .../influx/controller/S7DemoController.java | 78 +++++++ .../java/com/cnbm/influx/entity/Header.java | 30 +++ .../health/InfluxDB2HealthIndicator.java | 55 +++++ ...uxDB2HealthIndicatorAutoConfiguration.java | 58 +++++ .../AbstractInfluxDB2AutoConfiguration.java | 71 ++++++ .../influx/InfluxDB2AutoConfiguration.java | 60 +++++ .../InfluxDB2OkHttpClientBuilderProvider.java | 37 +++ .../influx/influx/InfluxDB2Properties.java | 178 +++++++++++++++ .../java/com/cnbm/influx/param/BaseParam.java | 24 ++ .../java/com/cnbm/influx/param/PageInfo.java | 24 ++ .../com/cnbm/influx/param/QueryDataParam.java | 31 +++ .../java/com/cnbm/influx/param/Range.java | 30 +++ .../main/java/com/cnbm/influx/param/Tag.java | 19 ++ .../java/com/cnbm/influx/template/Event.java | 24 ++ .../com/cnbm/influx/template/Temperature.java | 28 +++ .../src/main/resources/application-influx.yml | 17 ++ 28 files changed, 1404 insertions(+), 2 deletions(-) create mode 100644 ym-influx/pom.xml create mode 100644 ym-influx/src/main/java/Main2.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/Main.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/common/Utils.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/config/InfluxClient.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/constant/Constant.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/controller/S7DemoController.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/entity/Header.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicator.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicatorAutoConfiguration.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/influx/AbstractInfluxDB2AutoConfiguration.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2AutoConfiguration.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2OkHttpClientBuilderProvider.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2Properties.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/param/BaseParam.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/param/PageInfo.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/param/QueryDataParam.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/param/Range.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/param/Tag.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/template/Event.java create mode 100644 ym-influx/src/main/java/com/cnbm/influx/template/Temperature.java create mode 100644 ym-influx/src/main/resources/application-influx.yml diff --git a/pom.xml b/pom.xml index e3d74d3..d7b8a9f 100644 --- a/pom.xml +++ b/pom.xml @@ -14,6 +14,7 @@ ym-gateway ym-baisc ym-schedule-task + ym-influx pom @@ -89,6 +90,22 @@ spring-boot-configuration-processor true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + + com.fasterxml.jackson.core + jackson-databind + + + + + + redis.clients jedis diff --git a/ym-admin/src/main/java/com/cnbm/admin/config/SecurityConfig.java b/ym-admin/src/main/java/com/cnbm/admin/config/SecurityConfig.java index 2fff7b1..587a917 100644 --- a/ym-admin/src/main/java/com/cnbm/admin/config/SecurityConfig.java +++ b/ym-admin/src/main/java/com/cnbm/admin/config/SecurityConfig.java @@ -72,6 +72,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { "/swagger-ui/**", "/webjars/**", "/websocket/**", + "/influx/**", "/captcha").anonymous() // .antMatchers("/testCors").hasAuthority("system:dept:list222") // 除上面外的所有请求全部需要鉴权认证 diff --git a/ym-gateway/pom.xml b/ym-gateway/pom.xml index 2200520..db6f686 100644 --- a/ym-gateway/pom.xml +++ b/ym-gateway/pom.xml @@ -32,6 +32,26 @@ ym-baisc 1.0-SNAPSHOT + + com.cnbm + ym-influx + 1.0-SNAPSHOT + + + + + + + + + + + + + + + + com.cnbm ym-schedule-task diff --git a/ym-gateway/src/main/java/com/cnbm/config/SwaggerConfig.java b/ym-gateway/src/main/java/com/cnbm/config/SwaggerConfig.java index ae8c3fc..ad3a255 100644 --- a/ym-gateway/src/main/java/com/cnbm/config/SwaggerConfig.java +++ b/ym-gateway/src/main/java/com/cnbm/config/SwaggerConfig.java @@ -86,6 +86,22 @@ public class SwaggerConfig { .securitySchemes(Arrays.asList(new ApiKey("token", "token", "header"))); } + @Bean + public Docket influxApi() { + return new Docket(DocumentationType.SWAGGER_2) + .groupName("ym-influx") + .apiInfo(apiInfos("influx", "influx模块")) + .useDefaultResponseMessages(true) + .forCodeGeneration(false) + .select() + .apis(RequestHandlerSelectors.basePackage("com.cnbm.influx")) + .paths(PathSelectors.any()) + .build() + .securityContexts(Arrays.asList(securityContext())) + // ApiKey的name需与SecurityReference的reference保持一致 + .securitySchemes(Arrays.asList(new ApiKey("token", "token", "header"))); + } + /** * 创建该API的基本信息(这些基本信息会展现在文档页面中) * 访问地址:http://ip:port/swagger-ui.html diff --git a/ym-gateway/src/main/resources/application-dev.yml b/ym-gateway/src/main/resources/application-dev.yml index 7d20303..39984e5 100644 --- a/ym-gateway/src/main/resources/application-dev.yml +++ b/ym-gateway/src/main/resources/application-dev.yml @@ -37,4 +37,18 @@ spring: # driver-class-name: org.postgresql.Driver # url: jdbc:postgresql://123456:5432/renren_security # username: postgres -# password: 123456 \ No newline at end of file +# password: 123456 + +influx: + url: http://192.168.0.170:8086 # URL to connect to InfluxDB. + username: caixiang # Username to use in the basic auth. + password: 251128856 # Password to use in the basic auth. + token: lkBsC27QZr1W50BSPlGxpTqNNpwuUk5uz1dZZRPSPbCG5VmNDDUo8P3UkZIhGWwfJwkuz6ZGZ7Et4_KBaG3gHw== # Token to use for the authorization. + org: qgs # Default destination organization for writes and queries. + bucket: qgs-bucket # Default destination bucket for writes. + logLevel: BODY # The log level for logging the HTTP request and HTTP response. (Default: NONE) + readTimeout: 5s # Read timeout for OkHttpClient. (Default: 10s) + writeTimeout: 5s # Write timeout for OkHttpClient. (Default: 10s) + connectTimeout: 5s # Connection timeout for OkHttpClient. (Default: 10s) + + # management.health.influx.enabled=true # Whether to enable InfluxDB 2.x health check. \ No newline at end of file diff --git a/ym-gateway/src/main/resources/application.yml b/ym-gateway/src/main/resources/application.yml index b15afad..4e71122 100644 --- a/ym-gateway/src/main/resources/application.yml +++ b/ym-gateway/src/main/resources/application.yml @@ -73,4 +73,5 @@ mybatis-plus: logging: level: - com.cnbm.admin.dao: DEBUG \ No newline at end of file + com.cnbm.admin.dao: DEBUG + diff --git a/ym-influx/pom.xml b/ym-influx/pom.xml new file mode 100644 index 0000000..91fae60 --- /dev/null +++ b/ym-influx/pom.xml @@ -0,0 +1,76 @@ + + + + ym-pass + com.cnbm + 1.0-SNAPSHOT + + 4.0.0 + + ym-influx + + + 8 + 8 + + + + + + com.influxdb + influxdb-client-java + 6.3.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ym-influx/src/main/java/Main2.java b/ym-influx/src/main/java/Main2.java new file mode 100644 index 0000000..2c908e4 --- /dev/null +++ b/ym-influx/src/main/java/Main2.java @@ -0,0 +1,54 @@ +import com.cnbm.influx.config.InfluxClient; +import com.cnbm.influx.template.Event; +import com.influxdb.client.InfluxDBClient; +import com.influxdb.client.InfluxDBClientFactory; +import com.influxdb.client.WriteApi; +import com.influxdb.client.domain.WritePrecision; +import com.influxdb.client.write.Point; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/7/1 16:39 + */ +public class Main2 { + public static void main(String[] args) { + //方式1 + Point point = Point.measurement("ASProcessCompleteEvent") + .addTag("transationId", "112311") + .addTag("argName", "argName11") + .addField("argValue", 3D) + .time(Instant.now().toEpochMilli(), WritePrecision.MS); + InfluxClient.Client.getWriteApi().writePoint(point); + + +// //方式2 +// char[] token = "lkBsC27QZr1W50BSPlGxpTqNNpwuUk5uz1dZZRPSPbCG5VmNDDUo8P3UkZIhGWwfJwkuz6ZGZ7Et4_KBaG3gHw==".toCharArray(); +// String org = "qgs"; +// String bucket = "mytest"; +// InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://192.168.0.170:8086", token, org, bucket); +// WriteApi writeApi = influxDBClient.makeWriteApi(); +// Point point = Point.measurement("ASProcessCompleteEvent") +// .addTag("transationId", "112311") +// .addTag("argName", "argName11") +// .addField("argValue", 7D) +// .time(Instant.now().toEpochMilli(), WritePrecision.MS); +// +// +// Point point2 = Point.measurement("ASProcessCompleteEvent") +// .addTag("transationId", "222312") +// .addTag("argName", "argName11") +// .addField("argValue", 8D) +// .time(Instant.now().toEpochMilli(), WritePrecision.MS); +// List list = new ArrayList<>(); +// list.add(point); +// list.add(point2); +// writeApi.writePoints(list); +// //一定要close ,不如write 不了数据 +// influxDBClient.close(); + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/Main.java b/ym-influx/src/main/java/com/cnbm/influx/Main.java new file mode 100644 index 0000000..9b4f594 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/Main.java @@ -0,0 +1,214 @@ +package com.cnbm.influx; + +import com.cnbm.influx.config.InfluxClient; +import com.cnbm.influx.param.QueryDataParam; +import com.cnbm.influx.common.Utils; +import com.cnbm.influx.param.PageInfo; +import com.cnbm.influx.param.Range; +import com.cnbm.influx.param.Tag; + +import com.cnbm.influx.template.Event; +import com.influxdb.client.*; +import com.influxdb.client.domain.WritePrecision; +import com.influxdb.client.write.Point; +import com.influxdb.query.FluxRecord; +import com.influxdb.query.FluxTable; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.*; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/25 11:19 + */ +public class Main { + public static void main(String[] args) throws InterruptedException { + char[] token = "lkBsC27QZr1W50BSPlGxpTqNNpwuUk5uz1dZZRPSPbCG5VmNDDUo8P3UkZIhGWwfJwkuz6ZGZ7Et4_KBaG3gHw==".toCharArray(); + String org = "qgs"; + String bucket = "mytest"; + InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://192.168.0.170:8086", token, org, bucket); + + + WriteApi writeApi = influxDBClient.makeWriteApi(); + +// InfluxService influxService = new InfluxService(); +// Event event = new Event(); +// event.time = Instant.now(); +// event.transationId = "asas"; +// event.argName = "arg5"; +// event.argValue = new Double(11); +// influxService.insert(event); + +// Event event = new Event(); +// event.setTime(Instant.now()); +// event.setTransationId("asasd11"); +// event.setArgName("argName11"); +// event.setArgValue(3d); +// InfluxClient.Client.insert(event,"ASProcessCompleteEvent"); + + + Point point = Point.measurement("ASProcessCompleteEvent") + .addTag("transationId", "112311") + .addTag("argName", "argName11") + .addField("argValue", 3D) + .time(Instant.now().toEpochMilli(), WritePrecision.MS); + + + Point point2 = Point.measurement("ASProcessCompleteEvent") + .addTag("transationId", "222312") + .addTag("argName", "argName11") + .addField("argValue", 4D) + .time(Instant.now().toEpochMilli(), WritePrecision.MS); + List list = new ArrayList<>(); + list.add(point); + list.add(point2); + + writeApi.writePoints(list); + + //todo api.writeMeasurements(WritePrecision.NS, Arrays.asList(new H2OFeetMeasurement("coyote_creek", 15.0D, null, Instant.ofEpochSecond(0, 15)), new H2OFeetMeasurement("coyote_creek", 16.0D, null, Instant.ofEpochSecond(0, 16)))); +// List events = new ArrayList<>(); +// for(int i=0;i<99;i++){ +// +// Event event = new Event(); +// event.time = Instant.now(); +// event.transationId = "asas"+i; +// event.argName = "arg7"; +// event.argValue = new Double(i); +// events.add(event); +// } +// List qList = new ArrayList<>(); +// Event event = new Event(); +// event.time = Instant.now(); +// event.transationId = "asas"; +// event.argName = "arg7"; +// event.argValue = new Double(1); +// Thread.sleep(100); +// Event event2 = new Event(); +// event2.time = Instant.now(); +// event2.transationId = "asas"; +// event2.argName = "arg7"; +// event2.argValue = new Double(2); +// qList.add(event); +// qList.add(event2); +// writeApi.writeMeasurement( WritePrecision.NS, qList); + +// for(int i=0;i<10;i++){ +// Temperature temperature = new Temperature(); +// temperature.location = "south"; +// temperature.value = new Double(i); +// temperature.type = "equipment3"; +// temperature.time = Instant.now(); +// +// writeApi.writeMeasurement( WritePrecision.NS, temperature); +// } + + +// String flux = "from(bucket:\"mytest\") |> range(start: -60m)"; +// flux += "|> filter(fn: (r) =>\n" + +// " r._measurement == \"ASProcessCompleteEvent\" and \n" + +//// " r._field == \"type\" and \n" + //对应 Field key +// " r.argName == \"arg3\"\n" + //对应 Tags key (Tag 信息无法在FluxRecord 里面获取。) +// " )"; +// QueryApi queryApi = influxDBClient.getQueryApi(); +// +// List tables = queryApi.query(flux); +// for (FluxTable fluxTable : tables) { +// List records = fluxTable.getRecords(); +// for (FluxRecord fluxRecord : records) { +// System.out.println("time: "+fluxRecord.getTime() +" key:"+fluxRecord.getField()+" value: " + fluxRecord.getValueByKey("_value")+" measurement: " + fluxRecord.getMeasurement()); +//// System.out.println("time: "+fluxRecord.getTime() +" key:"++" value: " + fluxRecord.getValueByKey("_value")+" measurement: " + fluxRecord.getMeasurement()); +// +// } +// } + + +// from(bucket: "mytest") +// |> range(start: 2022-06-29T11:30:00Z, stop: 2022-06-29T12:30:00Z) +// |> filter(fn: (r) => r["_measurement"] == "ASProcessCompleteEvent") +// |> filter(fn: (r) => r["argName"] == "arg4") +// |> drop(columns: ["transationId"]) +// |> sort(columns: ["_time"], desc: true) +// 取前10条数据 +// |> limit(n: 10, offset: 0) + +// 取 10-20 条数据 +// |> limit(n: 10, offset: 10) + +// 取 20-30 条数据 +// |> limit(n: 10, offset: 20) + + + +// QueryDataParam queryDataParam = new QueryDataParam(); +// queryDataParam.setBucket("mytest"); +// queryDataParam.setRange(new Range(getDate().toInstant(),new Date().toInstant())); +// queryDataParam.setMeasurement("ASProcessCompleteEvent"); +// queryDataParam.setTag(new Tag("argName","arg4")); +// queryDataParam.setDropedTagName("transationId"); +// queryDataParam.setPageInfo(new PageInfo(1,100)); +// +// List tables = query(queryDataParam,influxDBClient); +// List records1 = tables.get(0).getRecords(); +// List> lists = Utils.fixedGroup(records1, 10); + +// for (FluxTable fluxTable : tables) { +// List records = fluxTable.getRecords(); +// for (FluxRecord fluxRecord : records) { +// System.out.println("time: "+fluxRecord.getTime() +" key:"+fluxRecord.getField()+" value: " + fluxRecord.getValueByKey("_value")+" measurement: " + fluxRecord.getMeasurement()); +// +// } +// } + + influxDBClient.close(); + } + + + public static Date getDate(){ + Date date = new Date();//获取当前日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//格式化一下 + Calendar calendar1 = Calendar.getInstance();//获取对日期操作的类对象 + //两种写法都可以获取到前三天的日期 + // calendar1.set(Calendar.DAY_OF_YEAR,calendar1.get(Calendar.DAY_OF_YEAR) -3); + //在当前时间的基础上获取前三天的日期 + calendar1.add(Calendar.DATE, -3); + //add方法 参数也可传入 月份,获取的是前几月或后几月的日期 + //calendar1.add(Calendar.MONTH, -3); + Date day = calendar1.getTime(); + return day; + } + + private static List query(QueryDataParam param,InfluxDBClient influxDBClient){ + String measurement = param.getMeasurement(); + String dropedTagName = param.getDropedTagName(); + Range range = param.getRange(); + String bucket = param.getBucket(); + String tagName = param.getTag().getTagName(); + String tagValue = param.getTag().getTagValue(); + PageInfo pageInfo = param.getPageInfo(); + + String flux = "from(bucket:\""+bucket+"\")"; + flux += "|> range(start: "+range.getBegin().toString()+",stop:"+range.getEnd().toString()+") \n"; + flux += "|> filter(fn: (r) => r[\"_measurement\"] == \""+measurement+"\") \n"; + flux += "|> filter(fn: (r) => r[\""+tagName+"\"] == \""+tagValue+"\") \n"; + flux += "|> drop(columns: [\""+dropedTagName+"\"]) \n"; + flux += "|> sort(columns: [\"_time\"], desc: true) \n"; + if(pageInfo!=null){ + flux += "|> limit(n: "+pageInfo.getSize()+", offset: "+(pageInfo.getCurrent()-1)* pageInfo.getSize()+")"; + } + + QueryApi queryApi = influxDBClient.getQueryApi(); + + List tables = queryApi.query(flux); + for (FluxTable fluxTable : tables) { + List records = fluxTable.getRecords(); + for (FluxRecord fluxRecord : records) { + System.out.println("time: "+fluxRecord.getTime() +" key:"+fluxRecord.getField()+" value: " + fluxRecord.getValueByKey("_value")+" measurement: " + fluxRecord.getMeasurement()); + + } + } + + return tables; + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/common/Utils.java b/ym-influx/src/main/java/com/cnbm/influx/common/Utils.java new file mode 100644 index 0000000..4d52dea --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/common/Utils.java @@ -0,0 +1,69 @@ +package com.cnbm.influx.common; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/29 16:23 + */ +public class Utils { + public static void main(String[] args) { + ArrayList arrs = new ArrayList<>(); + + for(int i=0;i<100;i++){ + arrs.add(i); + } + List> lists = fixedGroup(arrs, 10); + System.out.println(); + + } + + + public static Date getBeforeDate(Integer number){ + Date date = new Date();//获取当前日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//格式化一下 + Calendar calendar1 = Calendar.getInstance();//获取对日期操作的类对象 + //两种写法都可以获取到前三天的日期 + // calendar1.set(Calendar.DAY_OF_YEAR,calendar1.get(Calendar.DAY_OF_YEAR) -3); + //在当前时间的基础上获取前三天的日期 + calendar1.add(Calendar.DATE, 0-number); + //add方法 参数也可传入 月份,获取的是前几月或后几月的日期 + //calendar1.add(Calendar.MONTH, -3); + Date day = calendar1.getTime(); + return day; + } + + /** + * 将一组数据固定分组,每组n个元素 + * + * @param source 要分组的数据源 + * @param limit 每组n个元素 + * @param + * @return + */ + public static List> fixedGroup(List source, int limit) { + if (null == source || source.size() == 0 || limit <= 0) + return null; + List> result = new ArrayList>(); + int remainder = source.size() % limit; + int size = (source.size() / limit); + for (int i = 0; i < size; i++) { + List subset = null; + subset = source.subList(i * limit, (i + 1) * limit); + result.add(subset); + } + if (remainder > 0) { + List subset = null; + subset = source.subList(size * limit, size * limit + remainder); + result.add(subset); + } + return result; + } + + +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/config/InfluxClient.java b/ym-influx/src/main/java/com/cnbm/influx/config/InfluxClient.java new file mode 100644 index 0000000..a26dd81 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/config/InfluxClient.java @@ -0,0 +1,133 @@ +package com.cnbm.influx.config; + +import com.cnbm.influx.constant.Constant; +import com.cnbm.influx.param.PageInfo; +import com.cnbm.influx.param.QueryDataParam; +import com.cnbm.influx.param.Range; +import com.cnbm.influx.template.Event; +import com.influxdb.client.InfluxDBClient; +import com.influxdb.client.InfluxDBClientFactory; +import com.influxdb.client.QueryApi; +import com.influxdb.client.WriteApi; +import com.influxdb.client.domain.WritePrecision; +import com.influxdb.client.write.Point; +import com.influxdb.query.FluxTable; + +import java.util.ArrayList; +import java.util.List; + +public enum InfluxClient { + + /** + * influxdb 读写客户端,,如果write比较繁忙,后续可以考虑,维护 client一个线程池。 + * */ + Client("http://192.168.0.170:8086","lkBsC27QZr1W50BSPlGxpTqNNpwuUk5uz1dZZRPSPbCG5VmNDDUo8P3UkZIhGWwfJwkuz6ZGZ7Et4_KBaG3gHw==","qgs","qgs-bucket"), + + ; + private String url; + private String token; + private String org; + private String bucket; + + private InfluxDBClient influxDBClient; + private WriteApi writeApi; + + private QueryApi queryApi; + + InfluxClient(String url,String token,String org,String bucket){ + this.url = url; + this.token = token; + this.org = org; + this.bucket = bucket; + this.influxDBClient = InfluxDBClientFactory.create(this.url, this.token.toCharArray(),this.org,this.bucket); + this.writeApi = influxDBClient.makeWriteApi(); + this.queryApi = influxDBClient.getQueryApi(); + } + + + public QueryApi getQueryApi() { + return queryApi; + } + + public WriteApi getWriteApi() { + return writeApi; + } + + /** + * 测试连接是否正常 + * + * @return + * true 服务正常健康 + * false 异常 + */ + private boolean ping() { + boolean isConnected = false; + Boolean pong; + try { + pong = influxDBClient.ping(); + if (pong != null) { + isConnected = true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return isConnected; + } + + public void insert(Event event, String measurement){ + Point point = Point.measurement(measurement) + .addTag("transationId", event.getTransationId()) + .addTag("argName", event.getArgName()) + .addField("argValue", event.getArgValue()) + .time(event.getTime().toEpochMilli(), WritePrecision.MS); + writeApi.writePoint(point); + + } + + //异步 批量写入数据 + //如果要批量插入的话,一次也只能写入 + public void batchInsert(List events, String measurement){ + List list = new ArrayList<>(); + for(Event event:events){ + Point point = Point.measurement(measurement) + .addTag("transationId", event.getTransationId()) + .addTag("argName", event.getArgName()) + .addField("argValue", event.getArgValue()) + .time(event.getTime().toEpochMilli(), WritePrecision.MS); + list.add(point); + } + writeApi.writePoints(list); + } + + + public List query(QueryDataParam param){ + String measurement = param.getMeasurement(); + String dropedTagName = param.getDropedTagName(); + Range range = param.getRange(); + String bucket = param.getBucket(); + String tagName = param.getTag().getTagName(); + String tagValue = param.getTag().getTagValue(); + PageInfo pageInfo = param.getPageInfo(); + + String flux = "from(bucket:\""+bucket+"\")"; + flux += "|> range(start: "+range.getBegin()+",stop:"+range.getEnd()+")"; + flux += "|> filter(fn: (r) => r[\"_measurement\"] == \""+measurement+"\")"; + flux += "|> filter(fn: (r) => r[\""+tagName+"\"] == \""+tagValue+"\")"; + flux += "|> drop(columns: [\""+dropedTagName+"\"])"; + flux += "|> sort(columns: [\"_time\"], desc: true)"; + if(pageInfo!=null){ + flux += "|> limit(n: "+pageInfo.getSize()+", offset: "+(pageInfo.getCurrent()-1)* pageInfo.getSize()+")"; + } + + +// List tables = queryApi.query(flux); +// for (FluxTable fluxTable : tables) { +// List records = fluxTable.getRecords(); +// for (FluxRecord fluxRecord : records) { +// System.out.println("time: "+fluxRecord.getTime() +" key:"+fluxRecord.getField()+" value: " + fluxRecord.getValueByKey("_value")+" measurement: " + fluxRecord.getMeasurement()); +// +// } +// } + return queryApi.query(flux); + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/constant/Constant.java b/ym-influx/src/main/java/com/cnbm/influx/constant/Constant.java new file mode 100644 index 0000000..f8ed653 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/constant/Constant.java @@ -0,0 +1,23 @@ +package com.cnbm.influx.constant; + +import com.influxdb.LogLevel; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/7/1 9:18 + */ +public class Constant { + public static final String url = "http://192.168.0.170:8086"; + public static final String token = "lkBsC27QZr1W50BSPlGxpTqNNpwuUk5uz1dZZRPSPbCG5VmNDDUo8P3UkZIhGWwfJwkuz6ZGZ7Et4_KBaG3gHw=="; + public static final String org = "qgs"; + public static final String bucket = "qgs-bucket"; + public static final String username = "caixiang"; + public static final String password = "25112856"; + public static final LogLevel logLevel = LogLevel.BODY; + public static final LogLevel readTimeout = LogLevel.BODY; + public static final LogLevel writeTimeout = LogLevel.BODY; + public static final LogLevel connectTimeout = LogLevel.BODY; + + +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/controller/S7DemoController.java b/ym-influx/src/main/java/com/cnbm/influx/controller/S7DemoController.java new file mode 100644 index 0000000..966d208 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/controller/S7DemoController.java @@ -0,0 +1,78 @@ +package com.cnbm.influx.controller; + +import com.cnbm.influx.config.InfluxClient; +import com.cnbm.influx.template.Event; +import com.influxdb.client.InfluxDBClient; +import com.influxdb.client.domain.WritePrecision; +import com.influxdb.client.write.Point; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import java.time.Instant; + +@RestController +@RequestMapping("/influx") +public class S7DemoController { + private static final Logger logger = LoggerFactory.getLogger(S7DemoController.class); + + @Autowired + InfluxDBClient influxDBClient; + + +// try (WriteApi writeApi = influxDBClient.makeWriteApi()) { +// Temperature temperature = new Temperature(); +// temperature.setLocation("east"); +// temperature.setValue(106.2D); +// temperature.setTime(Instant.now()); +// writeApi.writeMeasurement(WritePrecision.NS,temperature); +// } +// +// try (WriteApi writeApi = influxDBClient.makeWriteApi()) { +// Point point = Point.measurement("temperature") +// .addTag("location","south") +// .addTag("owner","wxm") +// .addField("wxm",230.8); +// writeApi.writePoint(point); +// } + + + @PostMapping("/insertBatch") + public void insertBatch() throws InterruptedException { +// List list = new ArrayList<>(); +// +// for(int i=0;i<99;i++){ +// //Thread.sleep(1000); +// Event event = new Event(); +// event.time = Instant.now(); +// event.transationId = "asas"+i; +// event.argName = "arg5"; +// event.argValue = new Double(i); +// list.add(event); +// } +// influxService.batchInsert(list); + } + + + public Point insert(Event event, String measurement){ + Point point = Point.measurement(measurement) + .addTag("transationId", event.getTransationId()) + .addTag("argName", event.getArgName()) + .addField("argValue", event.getArgValue()) + .time(event.getTime().toEpochMilli(), WritePrecision.MS); + return point; + + } + @PostMapping("/insert") + public void insert() throws InterruptedException { + Event event = new Event(); + event.setTime(Instant.now()); + event.setTransationId("asasd11"); + event.setArgName("argName11"); + event.setArgValue(7d); + Point asProcessCompleteEvent = insert(event, "ASProcessCompleteEvent"); + influxDBClient.makeWriteApi().writePoint(asProcessCompleteEvent); + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/entity/Header.java b/ym-influx/src/main/java/com/cnbm/influx/entity/Header.java new file mode 100644 index 0000000..3caa845 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/entity/Header.java @@ -0,0 +1,30 @@ +package com.cnbm.influx.entity; + +import lombok.Data; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/27 10:46 + */ +@Data +public class Header { + + private String transationId; + + private String messageName; + + private String messageType; + + private String fromWhere; + + private String toWhere; + + private String equipmentId; + + private String sendTimestamp; + + private String argName; + + private Double argValue; +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicator.java b/ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicator.java new file mode 100644 index 0000000..27a1e19 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicator.java @@ -0,0 +1,55 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.cnbm.influx.health; + +import com.influxdb.client.InfluxDBClient; +import org.springframework.boot.actuate.health.AbstractHealthIndicator; +import org.springframework.boot.actuate.health.Health; +import org.springframework.util.Assert; + +/** + * {@link //HealthIndicator} for InfluxDB 2. + * + * @author Jakub Bednar (bednar@github) + */ +public class InfluxDB2HealthIndicator extends AbstractHealthIndicator { + + private final InfluxDBClient influxDBClient; + + public InfluxDB2HealthIndicator(final InfluxDBClient influxDBClient) { + super("InfluxDBClient 2 health check failed"); + Assert.notNull(influxDBClient, "InfluxDBClient must not be null"); + + this.influxDBClient = influxDBClient; + } + + @Override + protected void doHealthCheck(final Health.Builder builder) { + boolean success = this.influxDBClient.ping(); + + if (success) { + builder.up(); + } else { + builder.down(); + } + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicatorAutoConfiguration.java b/ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicatorAutoConfiguration.java new file mode 100644 index 0000000..bd2d439 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/health/InfluxDB2HealthIndicatorAutoConfiguration.java @@ -0,0 +1,58 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.cnbm.influx.health; + +import com.cnbm.influx.influx.InfluxDB2AutoConfiguration; +import com.influxdb.client.InfluxDBClient; +import org.springframework.boot.actuate.autoconfigure.health.CompositeHealthContributorConfiguration; +import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; +import org.springframework.boot.actuate.health.HealthContributor; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Map; + +/** + * {@link EnableAutoConfiguration Auto-configuration} for {@link InfluxDB2HealthIndicator}. + * + * @author Jakub Bednar + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnClass(InfluxDBClient.class) +@ConditionalOnBean(InfluxDBClient.class) +@ConditionalOnEnabledHealthIndicator("influx") +@AutoConfigureAfter(InfluxDB2AutoConfiguration.class) +public class InfluxDB2HealthIndicatorAutoConfiguration + extends CompositeHealthContributorConfiguration { + + @Bean + @ConditionalOnMissingBean(name = { "influxDB2HealthIndicator", "influxDB2HealthContributor" }) + public HealthContributor influxDbHealthContributor(final Map influxDBClients) { + return createContributor(influxDBClients); + } + +} \ No newline at end of file diff --git a/ym-influx/src/main/java/com/cnbm/influx/influx/AbstractInfluxDB2AutoConfiguration.java b/ym-influx/src/main/java/com/cnbm/influx/influx/AbstractInfluxDB2AutoConfiguration.java new file mode 100644 index 0000000..942d394 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/influx/AbstractInfluxDB2AutoConfiguration.java @@ -0,0 +1,71 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.cnbm.influx.influx; + +import com.influxdb.client.InfluxDBClientOptions; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import org.springframework.util.StringUtils; + +import javax.annotation.Nonnull; +import java.util.Collections; + +/** + * @author Jakub Bednar (04/08/2021 11:41) + */ +abstract class AbstractInfluxDB2AutoConfiguration { + protected final InfluxDB2Properties properties; + protected final InfluxDB2OkHttpClientBuilderProvider builderProvider; + + protected AbstractInfluxDB2AutoConfiguration(final InfluxDB2Properties properties, + final InfluxDB2OkHttpClientBuilderProvider builderProvider) { + this.properties = properties; + this.builderProvider = builderProvider; + } + + @Nonnull + protected InfluxDBClientOptions.Builder makeBuilder() { + OkHttpClient.Builder okHttpBuilder; + if (builderProvider == null) { + okHttpBuilder = new OkHttpClient.Builder() + .protocols(Collections.singletonList(Protocol.HTTP_1_1)) + .readTimeout(properties.getReadTimeout()) + .writeTimeout(properties.getWriteTimeout()) + .connectTimeout(properties.getConnectTimeout()); + } else { + okHttpBuilder = builderProvider.get(); + } + + InfluxDBClientOptions.Builder influxBuilder = InfluxDBClientOptions.builder() + .url(properties.getUrl()) + .bucket(properties.getBucket()) + .org(properties.getOrg()) + .okHttpClient(okHttpBuilder); + + if (StringUtils.hasLength(properties.getToken())) { + influxBuilder.authenticateToken(properties.getToken().toCharArray()); + } else if (StringUtils.hasLength(properties.getUsername()) && StringUtils.hasLength(properties.getPassword())) { + influxBuilder.authenticate(properties.getUsername(), properties.getPassword().toCharArray()); + } + return influxBuilder; + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2AutoConfiguration.java b/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2AutoConfiguration.java new file mode 100644 index 0000000..8635d4f --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2AutoConfiguration.java @@ -0,0 +1,60 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.cnbm.influx.influx; + +import com.influxdb.client.InfluxDBClient; +import com.influxdb.client.InfluxDBClientFactory; +import com.influxdb.client.InfluxDBClientOptions; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * {@link EnableAutoConfiguration Auto-configuration} for InfluxDB 2. + * + * @author Jakub Bednar (bednar@github) (06/05/2019 13:09) + */ +@Configuration +@ConditionalOnClass(InfluxDBClient.class) +@EnableConfigurationProperties(InfluxDB2Properties.class) +public class InfluxDB2AutoConfiguration extends AbstractInfluxDB2AutoConfiguration { + + public InfluxDB2AutoConfiguration(final InfluxDB2Properties properties, + final ObjectProvider builderProvider) { + super(properties, builderProvider.getIfAvailable()); + } + + @Bean + @ConditionalOnProperty("influx.url") + @ConditionalOnMissingBean(InfluxDBClient.class) + public InfluxDBClient influxDBClient() { + + InfluxDBClientOptions.Builder influxBuilder = makeBuilder(); + + return InfluxDBClientFactory.create(influxBuilder.build()).setLogLevel(properties.getLogLevel()); + } +} \ No newline at end of file diff --git a/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2OkHttpClientBuilderProvider.java b/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2OkHttpClientBuilderProvider.java new file mode 100644 index 0000000..db6fb5a --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2OkHttpClientBuilderProvider.java @@ -0,0 +1,37 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.cnbm.influx.influx; + +import okhttp3.OkHttpClient; + +import java.util.function.Supplier; + +/** + * Provide the {@link OkHttpClient.Builder OkHttpClient.Builder} to use to + * customize the auto-configured {@link com.influxdb.client.InfluxDBClient} instance. + * + * @author Jakub Bednar (bednar@github) (06/05/2019 13:11) + */ +@FunctionalInterface +public interface InfluxDB2OkHttpClientBuilderProvider extends Supplier { + +} \ No newline at end of file diff --git a/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2Properties.java b/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2Properties.java new file mode 100644 index 0000000..9e3f6dc --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/influx/InfluxDB2Properties.java @@ -0,0 +1,178 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.cnbm.influx.influx; + +import com.cnbm.influx.constant.Constant; +import com.influxdb.LogLevel; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +/** + * Configuration properties for InfluxDB 2. + * + * @author Jakub Bednar (bednar@github) (06/05/2019 12:54) + */ +@ConfigurationProperties(prefix = "influx") +public class InfluxDB2Properties { + +// public InfluxDB2Properties{ +// this.bucket = Constant.bucket; +// this.url = Constant.url; +// this.org = Constant.org; +// this.token = Constant.token; +// this.username = Constant.username; +// this.password = Constant.password; +// } + + private static final int DEFAULT_TIMEOUT = 10_000; + + /** + * URL to connect to InfluxDB. + */ + private String url = Constant.url; + + /** + * Username to use in the basic auth. + */ + private String username = Constant.username; + + /** + * Password to use in the basic auth. + */ + private String password = Constant.password; + + /** + * Token to use for the authorization. + */ + private String token = Constant.token; + + /** + * Default destination organization for writes and queries. + */ + private String org = Constant.org; + + /** + * Default destination bucket for writes. + */ + private String bucket = Constant.bucket; + + /** + * The log level for logging the HTTP request and HTTP response. + */ + private LogLevel logLevel = LogLevel.NONE; + + /** + * Read timeout for {@code OkHttpClient}. + */ + private Duration readTimeout = Duration.ofMillis(DEFAULT_TIMEOUT); + + /** + * Write timeout for {@code OkHttpClient}. + */ + private Duration writeTimeout = Duration.ofMillis(DEFAULT_TIMEOUT); + + /** + * Connection timeout for {@code OkHttpClient}. + */ + private Duration connectTimeout = Duration.ofMillis(DEFAULT_TIMEOUT); + + public String getUrl() { + return url; + } + + public void setUrl(final String url) { + this.url = url; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + + public String getToken() { + return token; + } + + public void setToken(final String token) { + this.token = token; + } + + public LogLevel getLogLevel() { + return logLevel; + } + + public void setLogLevel(final LogLevel logLevel) { + this.logLevel = logLevel; + } + + public String getOrg() { + return org; + } + + public void setOrg(final String org) { + this.org = org; + } + + public String getBucket() { + return bucket; + } + + public void setBucket(final String bucket) { + this.bucket = bucket; + } + + public Duration getReadTimeout() { + return readTimeout; + } + + public void setReadTimeout(final Duration readTimeout) { + this.readTimeout = readTimeout; + } + + public Duration getWriteTimeout() { + return writeTimeout; + } + + public void setWriteTimeout(final Duration writeTimeout) { + this.writeTimeout = writeTimeout; + } + + public Duration getConnectTimeout() { + return connectTimeout; + } + + public void setConnectTimeout(final Duration connectTimeout) { + this.connectTimeout = connectTimeout; + } +} \ No newline at end of file diff --git a/ym-influx/src/main/java/com/cnbm/influx/param/BaseParam.java b/ym-influx/src/main/java/com/cnbm/influx/param/BaseParam.java new file mode 100644 index 0000000..efcc9d4 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/param/BaseParam.java @@ -0,0 +1,24 @@ +package com.cnbm.influx.param; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/29 10:18 + */ +@Data +public class BaseParam implements Serializable { + //page 信息可选 + private PageInfo pageInfo; + + @NotEmpty(message = "measurement 不能为空") + private String measurement; + + @NotNull(message = "查询时间段不能为空") + private Range range; +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/param/PageInfo.java b/ym-influx/src/main/java/com/cnbm/influx/param/PageInfo.java new file mode 100644 index 0000000..5123a6a --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/param/PageInfo.java @@ -0,0 +1,24 @@ +package com.cnbm.influx.param; + +import lombok.Data; +import org.hibernate.validator.constraints.Range; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/29 10:19 + */ +@Data +public class PageInfo { + @Range(min = 1, message = "页码必须大于等于1") + private Integer current; + +// @NotNull(message = "每页显示条数不能为空") + @Range(min = 1, max = 1000, message = "每页显示条数范围需在1-1000之间") + private Integer size; + + public PageInfo(Integer current,Integer size){ + this.current = current; + this.size = size; + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/param/QueryDataParam.java b/ym-influx/src/main/java/com/cnbm/influx/param/QueryDataParam.java new file mode 100644 index 0000000..b2d011d --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/param/QueryDataParam.java @@ -0,0 +1,31 @@ +package com.cnbm.influx.param; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +/** + * @Desc: "influx 查询条件构造" + * @Author: caixiang + * @DATE: 2022/6/29 10:17 + * + * 注意: + * 必填 + * ① measurement 不能为空 + * ② 时间段 不能为空 + * ③ bucket 不能为空 + * 非必填 + * ① 分页信息可选 + * ② tag + * + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +public class QueryDataParam extends BaseParam{ + private Tag tag; + //查询的时候,需要忽略的字段。(transationId是唯一标识会对 最终的查询结果集产生影响) + private String dropedTagName; + private String bucket; + +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/param/Range.java b/ym-influx/src/main/java/com/cnbm/influx/param/Range.java new file mode 100644 index 0000000..4450c46 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/param/Range.java @@ -0,0 +1,30 @@ +package com.cnbm.influx.param; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.time.Instant; + +/** + * @Desc: "influxdb查询 时间范围" + * @Author: caixiang + * @DATE: 2022/6/29 11:14 + */ +@Data +public class Range { + @NotNull(message = "起始时间不能为空") + private Instant begin; + + @NotNull(message = "终点时间不能为空") + private Instant end; + + public Range(Instant begin,Instant end){ + this.begin = begin; + this.end = end; + } + +// public static void main(String[] args) { +// Date date = new Date(); +// System.out.println(date.toInstant().toString()); +// } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/param/Tag.java b/ym-influx/src/main/java/com/cnbm/influx/param/Tag.java new file mode 100644 index 0000000..fea0ab9 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/param/Tag.java @@ -0,0 +1,19 @@ +package com.cnbm.influx.param; + +import lombok.Data; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/29 14:38 + */ +@Data +public class Tag { + private String tagName; + private String tagValue; + + public Tag(String tagName,String tagValue){ + this.tagName = tagName; + this.tagValue = tagValue; + } +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/template/Event.java b/ym-influx/src/main/java/com/cnbm/influx/template/Event.java new file mode 100644 index 0000000..8595a1c --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/template/Event.java @@ -0,0 +1,24 @@ +package com.cnbm.influx.template; + +import com.influxdb.annotations.Column; +import com.influxdb.annotations.Measurement; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.time.Instant; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/25 11:13 + */ +@Data +public class Event { + private Instant time; + + private String transationId; + + private String argName; + + private Double argValue; +} diff --git a/ym-influx/src/main/java/com/cnbm/influx/template/Temperature.java b/ym-influx/src/main/java/com/cnbm/influx/template/Temperature.java new file mode 100644 index 0000000..32a3238 --- /dev/null +++ b/ym-influx/src/main/java/com/cnbm/influx/template/Temperature.java @@ -0,0 +1,28 @@ +package com.cnbm.influx.template; + +import com.influxdb.annotations.Column; +import com.influxdb.annotations.Measurement; + +import java.time.Instant; + +/** + * @Desc: "" + * @Author: caixiang + * @DATE: 2022/6/22 15:52 + */ +//Temperature.java +@Measurement(name = "temperature") +public class Temperature { + + @Column(tag = true) + public String location; + + @Column + public Double value; + + @Column + public String type; + + @Column(timestamp = true) + public Instant time; +} diff --git a/ym-influx/src/main/resources/application-influx.yml b/ym-influx/src/main/resources/application-influx.yml new file mode 100644 index 0000000..3c0f8bf --- /dev/null +++ b/ym-influx/src/main/resources/application-influx.yml @@ -0,0 +1,17 @@ +influx: + url: http://192.168.0.170:8086 # URL to connect to InfluxDB. + username: caixiang # Username to use in the basic auth. + password: 251128856 # Password to use in the basic auth. + token: lkBsC27QZr1W50BSPlGxpTqNNpwuUk5uz1dZZRPSPbCG5VmNDDUo8P3UkZIhGWwfJwkuz6ZGZ7Et4_KBaG3gHw== # Token to use for the authorization. + org: qgs # Default destination organization for writes and queries. + bucket: qgs-bucket # Default destination bucket for writes. + logLevel: BODY # The log level for logging the HTTP request and HTTP response. (Default: NONE) + readTimeout: 5s # Read timeout for OkHttpClient. (Default: 10s) + writeTimeout: 5s # Write timeout for OkHttpClient. (Default: 10s) + connectTimeout: 5s # Connection timeout for OkHttpClient. (Default: 10s) + + # management.health.influx.enabled=true # Whether to enable InfluxDB 2.x health check. +management: + health: + influxdb: + enabled: true \ No newline at end of file