InfluxDB持久层封装

embedded/2024/10/18 15:46:53/

InfluxDB持久层封装

了解如何使用spring-boot来操作InfluxDB数据库,首先我们来看下整个的系统结构图例:

在这里插入图片描述

对比下mybatis中的执行流程:

在这里插入图片描述

1_自动装配

首先,我们来看下第一步自动装配:依赖spring-boot自动装配出InfluxDB对象,并把对象交于IOC容器管理,对于spring-boot来说它最大的特点就是自动装配,这里我们用到2个类:配置文件类InfluxDbProperties,配置类InfluxDbAutoConfiguration,如下图所示:

在这里插入图片描述

spring-boot-autoconfigure中已经构建好对应的类信息,下面我们逐一解读一下,首先我们看下 InfluxDbProperties 配置:

java">package org.springframework.boot.autoconfigure.influx;import org.springframework.boot.context.properties.ConfigurationProperties;/*** Configuration properties for InfluxDB*/
@ConfigurationProperties(prefix = "spring.influx")
public class InfluxDbProperties {/*** URL of the InfluxDB instance to which to connect.*/private String url;/*** Login user.*/private String user;/*** Login password.*/private String password;/*** setter、getter略*/
}

当我们在使用时,只需要在对应项目的bootstrap.yml文件做如下配置:

spring:influx:url: http://192.168.193.141:8086password: 123456user: admin

spring-boot 在发现我们引入 InfluxDB.class 后自动按照 InfluxDbProperties 的属性帮我们构建InfluxDB 对象交于spring-IOC容器

java">package org.springframework.boot.autoconfigure.influx;@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(InfluxDB.class)
@EnableConfigurationProperties(InfluxDbProperties.class)
public class InfluxDbAutoConfiguration {@Bean@ConditionalOnMissingBean@ConditionalOnProperty("spring.influx.url")public InfluxDB influxDb(InfluxDbProperties properties,ObjectProvider<InfluxDbOkHttpClientBuilderProvider> builder) {return new InfluxDBImpl(properties.getUrl(), properties.getUser(), properties.getPassword(),determineBuilder(builder.getIfAvailable()));}private static OkHttpClient.Builder determineBuilder(InfluxDbOkHttpClientBuilderProvider builder) {if (builder != null) {return builder.get();}return new OkHttpClient.Builder();}}

2_配置管理

构建好InfluxDB 对象后,那如何使用呢?下面我们来看下第二步配置管理:项目启动时,通过InfluxDBConfig构建出业务执行器、参数处理器、结果处理器,并把对象交于IOC容器管理,framework-influxdb项目中我们构建了一个InfluxDBConfig配置类,内容如下:

java">package org.example.influxDd.config;import org.example.influxDd.core.Executor;
import org.example.influxDd.core.ParameterHandler;
import org.example.influxDd.core.ResultSetHandler;
import org.influxdb.InfluxDB;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 时序数据库配置类*/
@Configuration
public class InfluxDBConfig {@Bean(name = "executor")public Executor executor(InfluxDB influxDB) {return new Executor(influxDB);}@Bean(name = "parameterHandler")public ParameterHandler parameterHandler(InfluxDB influxDB) {return new ParameterHandler();}@Bean(name = "resultSetHandler")public ResultSetHandler resultSetHandler(InfluxDB influxDB) {return new ResultSetHandler();}
}

将其配置到自动装配文件META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.influxDd.config.InfluxDBConfig

业务执行器Executor :需要从spring-IOC中拿到InfluxDB来完成构建,用于与influxDB进行交互

java">package org.example.influxDd.core;import lombok.extern.slf4j.Slf4j;
import org.example.influxDd.util.EmptyUtil;
import org.influxdb.InfluxDB;
import org.influxdb.annotation.Measurement;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 执行器*/
@Slf4j
public class Executor {InfluxDB influxDB;public Executor() {}public Executor(InfluxDB influxDB) {this.influxDB = influxDB;}public List<Map<String,Object>> select(String sql,String database) {QueryResult queryResult = influxDB.query(new Query(sql, database));List<Map<String,Object>> resultList = new ArrayList<>();queryResult.getResults().forEach(result -> {//查询出错抛出错误信息if (!EmptyUtil.isNullOrEmpty(result.getError())){throw new RuntimeException(result.getError());}if (!EmptyUtil.isNullOrEmpty(result)&&!EmptyUtil.isNullOrEmpty(result.getSeries())){//获取所有列的集合,一个迭代是代表一组List<QueryResult.Series> series= result.getSeries();for (QueryResult.Series s : series) {//列中含有多行数据,每行数据含有多列value,所以嵌套ListList<List<Object>> values = s.getValues();//每组的列是固定的List<String> columns = s.getColumns();for (List<Object> v:values){//循环遍历结果集,获取每行对应的value,以map形式保存Map<String,Object> queryMap =new HashMap<String, Object>();for(int i=0;i<columns.size();i++){//遍历所有列名,获取列对应的值String column = columns.get(i);if (v.get(i)==null||v.get(i).equals("null")){//如果是null就存入nullqueryMap.put(column,null);}else {//不是null就转成字符串存储String value = String.valueOf(v.get(i));//如果是时间戳还可以格式转换,我这里懒了queryMap.put(column, value);}}//把结果添加到结果集中resultList.add(queryMap);}}}});return resultList;}public void insert(Object args[]) {if (args.length != 1) {throw new RuntimeException();}Object obj = args[0];List<Object> list = new ArrayList<>();if (obj instanceof List){list = (ArrayList) obj;}else {list.add(obj);}if (list.size() > 0) {Object firstObj = list.get(0);Class<?> domainClass = firstObj.getClass();List<Point> pointList = new ArrayList<>();for (Object o : list) {Point point = Point.measurementByPOJO(domainClass).addFieldsFromPOJO(o).build();pointList.add(point);}//获取数据库名和rpMeasurement measurement = firstObj.getClass().getAnnotation(Measurement.class);String database = measurement.database();String retentionPolicy = measurement.retentionPolicy();BatchPoints batchPoints = BatchPoints.builder().points(pointList).retentionPolicy(retentionPolicy).build();influxDB.setDatabase(database);influxDB.write(batchPoints);}}public void delete(String sql, String database) {influxDB.query(new Query(sql, database));}}

参数处理器 ParameterHandler :用于执行参数的封装处理

java">package org.example.influxDd.core;import org.example.influxDd.anno.Param;import java.lang.reflect.Parameter;/*** 参数处理器*/
public class ParameterHandler {/*** 拼接sql** @param parameters 参数名* @param args       参数实际值* @param sql        未拼接参数的sql语句* @return 拼接好的sql*/public String handleParameter(Parameter[] parameters, Object[] args, String sql) {for (int i = 0; i < parameters.length; i++) {Class<?> parameterType = parameters[i].getType();String parameterName = parameters[i].getName();Param param = parameters[i].getAnnotation(Param.class);if (param != null) {parameterName = param.value();}if (parameterType == String.class) {sql = sql.replaceAll("\\#\\{" + parameterName + "\\}", "'" + args[i] + "'");sql = sql.replaceAll("\\$\\{" + parameterName + "\\}", args[i].toString());} else {sql = sql.replaceAll("\\#\\{" + parameterName + "\\}", args[i].toString());sql = sql.replaceAll("\\$\\{" + parameterName + "\\}", args[i].toString());}}return sql;}
}

参数处理器配合参数注解使用:

java">package org.example.influxDd.anno;import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@Documented
public @interface Param {String value();
}

结果处理器ResultSetHandler :用于执行结构的封装处理

java">package org.example.influxDd.core;import lombok.SneakyThrows;
import org.example.influxDd.util.BeanConv;
import org.example.influxDd.util.EmptyUtil;import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 结果集处理器*/
public class ResultSetHandler {/**** @Description 结果处理** @param reultList influx返回结果* @param method 目标方法* @param sql 执行sql* @param resultType 注解声明返回类型* @return*  java.lang.Object*/@SneakyThrowspublic Object handleResultSet(List<Map<String,Object>> reultList, Method method, String sql, Class<?> resultType) {Class<?> returnTypeTarget = method.getReturnType();//如果结果为空直接返回空构建if (EmptyUtil.isNullOrEmpty(reultList)){if (returnTypeTarget== List.class){return new ArrayList<>();}else if (returnTypeTarget==Map.class){return new HashMap<>();}else if (returnTypeTarget==String.class){return null;}else {return convertStringToObject(resultType,"0");}}//当前method声明返回结果不为list,且resultType与method声明返回结果类型不匹配if (returnTypeTarget!= List.class&&resultType!=returnTypeTarget){throw  new RuntimeException("返回类型与声明返回类型不匹配");}//当前method声明返回结果不为list,且resultType与method声明返回结果类型匹配if (returnTypeTarget!= List.class&&resultType==returnTypeTarget){//结果不唯一则抛出异常if (reultList.size()!=1){throw  new RuntimeException("返回结果不唯一");}//驼峰处理Map<String, Object> mapHandler = convertKeysToCamelCase(reultList.get(0));//单个Map类型if (resultType==Map.class){return mapHandler;//单个自定义类型} else if (!isTargetClass(resultType)){return BeanConv.toBean(mapHandler, resultType);//单个JDK提供指定类型}else {if (mapHandler.size()!=2){throw  new RuntimeException("返回结果非单值");}for (String key : mapHandler.keySet()) {if (!key.equals("time")&&!EmptyUtil.isNullOrEmpty((mapHandler.get(key)))){String target = String.valueOf(mapHandler.get(key)).replace(".0","");return convertStringToObject(resultType,target);}}}}//当前method声明返回结果为listif (returnTypeTarget== List.class){//驼峰处理List<Map<String, Object>> listHandler = convertKeysToCamelCase(reultList);//list的内部为map结果if (resultType==Map.class){return listHandler;//list的内部为自定义类型}else if (!isTargetClass(resultType)){return BeanConv.toBeanList(listHandler, resultType);//list的内部为JDK提供指定类型}else {List<Object> listResult = new ArrayList<>();listHandler.forEach(mapHandler->{if (mapHandler.size()!=2){throw  new RuntimeException("返回结果非单值");}for (String key : mapHandler.keySet()) {if (!key.equals("time")&&!EmptyUtil.isNullOrEmpty((mapHandler.get(key)))){String target = String.valueOf(mapHandler.get(key)).replace(".0","");listResult.add(convertStringToObject(resultType,target));}}});return listResult;}}return  null;}// 检查类是否是目标类型public static boolean isTargetClass(Class<?> clazz) {return clazz == Integer.class ||clazz == int.class ||clazz == Long.class ||clazz == long.class ||clazz == Float.class ||clazz == float.class ||clazz == Double.class ||clazz == double.class ||clazz == Short.class ||clazz == short.class ||clazz == Byte.class ||clazz == byte.class ||clazz == Character.class ||clazz == char.class ||clazz == Boolean.class||clazz == boolean.class||clazz== BigDecimal.class ||clazz== String.class;}public static Map<String, Object> convertKeysToCamelCase(Map<String, Object> map) {Map<String, Object> camelCaseMap = new HashMap<>();for (Map.Entry<String, Object> entry : map.entrySet()) {String originalKey = entry.getKey();Object value = entry.getValue();String camelCaseKey = convertToCamelCase(originalKey);camelCaseMap.put(camelCaseKey, value);}return camelCaseMap;}public static List<Map<String, Object>> convertKeysToCamelCase(List<Map<String, Object>> mapList) {List<Map<String, Object>> listHandler = new ArrayList<>();mapList.forEach(n->{listHandler.add(convertKeysToCamelCase(n));});return listHandler;}public static String convertToCamelCase(String snakeCase) {StringBuilder camelCase = new StringBuilder();boolean nextUpperCase = false;for (int i = 0; i < snakeCase.length(); i++) {char currentChar = snakeCase.charAt(i);if (currentChar == '_') {nextUpperCase = true;} else {if (nextUpperCase) {camelCase.append(Character.toUpperCase(currentChar));nextUpperCase = false;} else {camelCase.append(Character.toLowerCase(currentChar));}}}return camelCase.toString();}@SneakyThrowspublic static <T> T convertStringToObject(Class<?> clazz, String str){if (clazz == String.class) {return (T)str; // 如果目标类型是 String,则直接返回字符串} else if (isTargetClass(clazz)){// 获取目标类型的构造函数,参数为 String 类型的参数Constructor<?> constructor = clazz.getConstructor(String.class);return (T)constructor.newInstance(str); // 使用构造函数创建目标类型的对象}else {return (T)clazz.newInstance();}}
}

3_切面处理

下面我们来看下第三步切面处理:业务系统service调用业务Mapper时,influxDBAspect会对被@ S e l e c t Select Select @ I n s e r t @Insert @Insert注解的方法进行切面处理,封装构建参数处理器,然后通过业务执行器请求influxDB,最后交于结果处理器来封装数据。在进行前面之前我们定义了2个注解@Select 和@Insert内容如下:

java">package org.example.influxDd.anno;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Select {//执行的influxQLString value();//返回的类型Class resultType();//执行的目标库String database();
}

Insert:

java">package org.example.influxDd.anno;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Insert {
}

当Mapper中的方法被调用时,会被定义的InfluxDBAspect切面拦截处理:

java">package org.example.influxDd.aspect;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.influxDd.anno.Insert;
import org.example.influxDd.anno.Select;
import org.example.influxDd.core.Executor;
import org.example.influxDd.core.ParameterHandler;
import org.example.influxDd.core.ResultSetHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.Map;/*** @ClassName InfluxDBAspect.java* @Description 拦截influxDb操作*/
@Aspect
@Component
public class InfluxDBAspect {private final Executor executor;private final ParameterHandler parameterHandler;private final ResultSetHandler resultSetHandler;@Autowiredpublic InfluxDBAspect(Executor executor, ParameterHandler parameterHandler, ResultSetHandler resultSetHandler) {this.executor = executor;this.parameterHandler = parameterHandler;this.resultSetHandler = resultSetHandler;}@Around("@annotation(select)")public Object select(ProceedingJoinPoint joinPoint, Select select) {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();Method method = methodSignature.getMethod();Select selectAnnotation = method.getAnnotation(Select.class);//获得执行参数Parameter[] parameters = method.getParameters();//获得执行参数值Object[] args = joinPoint.getArgs();//获得执行sqlString sql = selectAnnotation.value();//替换参数sql = parameterHandler.handleParameter(parameters,args,sql);//注解声明返回类型Class<?> resultType = selectAnnotation.resultType();//查询结果List<Map<String,Object>> reultList = executor.select(sql,selectAnnotation.database());//根据返回类型返回结果return resultSetHandler.handleResultSet(reultList, method,sql,resultType);}@Around("@annotation(insert)")public void insert(ProceedingJoinPoint joinPoint, Insert insert) {//获得执行参数值Object[] args = joinPoint.getArgs();executor.insert(args);}
}

当切面select方法处理就可以通过反射拿到参数、sql、返回类型,然后通过 executor 来进行执行对应查询,而executor 中通过 parameterHandler 参数处理器解析参数,最后通过 resultSetHandler 结果处理器完成结果的处理。

4_其他工具的封装以及依赖

项目的结构如下:

framework-influxdb
└─src├─main├─java│  └─org│      └─example│          └─influxDd│              ├─anno│              ├─aspect│              ├─config│              ├─core│              └─util└─resources└─META-INF

操作influxDB的基础接口:

java">package org.example.influxDd;import org.example.influxDd.anno.Insert;import java.util.List;public interface InfluxDBBaseMapper<T> {@Insertvoid insertOne(T entity);@Insertvoid insertBatch(List<T> entityList);
}

对象转换工具

java">package org.example.influxDd.util;//这里想要使用mp的分页进行完善,不过还没有完成,可删除
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.Type;
import org.springframework.beans.BeanUtils;import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;/**** @description 对象转换工具,当对象成员变量属性:名称及类型相同时候会自动* 填充其值**/
@Slf4j
public class BeanConv {private static MapperFacade mapper;private static MapperFacade notNullMapper;static {MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();ConverterFactory converterFactory = mapperFactory.getConverterFactory();converterFactory.registerConverter(new LocalDateTimeConverter());converterFactory.registerConverter(new LocalDateConverter());converterFactory.registerConverter(new LocalTimeConverter());mapper = mapperFactory.getMapperFacade();MapperFactory notNullMapperFactory = new DefaultMapperFactory.Builder().mapNulls(false).build();notNullMapper = notNullMapperFactory.getMapperFacade();}private static class LocalDateTimeConverter extends BidirectionalConverter<LocalDateTime, LocalDateTime> {@Overridepublic LocalDateTime convertTo(LocalDateTime localDateTime, Type<LocalDateTime> type, MappingContext mappingContext) {return LocalDateTime.from(localDateTime);}@Overridepublic LocalDateTime convertFrom(LocalDateTime localDateTime, Type<LocalDateTime> type, MappingContext mappingContext) {return LocalDateTime.from(localDateTime);}}private static class LocalDateConverter extends BidirectionalConverter<LocalDate, LocalDate> {@Overridepublic LocalDate convertTo(LocalDate localDate, Type<LocalDate> type, MappingContext mappingContext) {return LocalDate.from(localDate);}@Overridepublic LocalDate convertFrom(LocalDate localDate, Type<LocalDate> type, MappingContext mappingContext) {return LocalDate.from(localDate);}}private static class LocalTimeConverter extends BidirectionalConverter<LocalTime, LocalTime> {@Overridepublic LocalTime convertTo(LocalTime localTime, Type<LocalTime> type, MappingContext mappingContext) {return LocalTime.from(localTime);}@Overridepublic LocalTime convertFrom(LocalTime localTime, Type<LocalTime> type, MappingContext mappingContext) {return LocalTime.from(localTime);}}/*** @Description 异常转换工具*/static class ExceptionsUtil {/**** <b>方法名:</b>:getStackTraceAsString<br>* <b>功能说明:</b>:将ErrorStack转化为String<br>*/public static String getStackTraceAsString(Exception e) {StringWriter stringWriter = new StringWriter();e.printStackTrace(new PrintWriter(stringWriter));return stringWriter.toString();}}/*** 分页对象复制* @param source      源对象* @param destinationClass 目标对象类型*/public static <S,D> Page<D> toPage(Page<S> source, Class<D> destinationClass) {if (EmptyUtil.isNullOrEmpty(source)){return null;}Class<? extends Page> handlerClass = source.getClass();Page<D> destination = mapper.map(source, handlerClass);destination.setRecords(mapper.mapAsList(source.getRecords(),destinationClass));return destination;}/**** @description 深度复制对象** @param source 源对象* @param destinationClass 目标类型* @return*/public static <T> T toBean(Object source, Class<T> destinationClass) {if (EmptyUtil.isNullOrEmpty(source)){return null;}return mapper.map(source, destinationClass);}/**** @description 深度复制对象** @param source 源对象* @param destinationClass 目标类型* @return*/public static <T> T toBean(Object source, Class<T> destinationClass, String... fieldsToIgnore) {try {T t = destinationClass.getDeclaredConstructor().newInstance();BeanUtils.copyProperties(source, t, fieldsToIgnore);return t;}catch (Exception e){ExceptionsUtil.getStackTraceAsString(e);return null;}}/**** @description 复制List** @param sourceList 源list对象* @param destinationClass 目标类型* @return*/public static <T> List<T> toBeanList(List<?> sourceList, Class<T> destinationClass) {if (EmptyUtil.isNullOrEmpty(sourceList)){return new ArrayList<>();}return mapper.mapAsList(sourceList,destinationClass);}}

判空工具:

java">package org.example.influxDd.util;import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;/*** @Description 判断对象是否为空的工具类*/
public abstract class EmptyUtil {/**** @description 对string字符串是否为空判断** @param str 被判定字符串* @return*/public static boolean isNullOrEmpty(String str) {if (str == null || "".equals(str.trim()) || "null".equalsIgnoreCase(str.trim()) || "undefined".equalsIgnoreCase(str.trim())) {return true;} else {return false;}}/**** @description 对于StringBuffer类型的非空判断** @param str 被判定StringBuffer* @return*/public static boolean isNullOrEmpty(StringBuffer str) {return (str == null || str.length() == 0);}/**** @description 对于string数组类型的非空判断** @param str 被判定字符串数组* @return*/public static boolean isNullOrEmpty(String[] str) {if (str == null || str.length == 0) {return true;} else {return false;}}/**** @description 对于Object类型的非空判断** @param obj 被判定对象* @return*/public static boolean isNullOrEmpty(Object obj) {if (obj == null || "".equals(obj)) {return true;} else {return false;}}/**** @description 对于Object数组类型的非空判断** @param obj 被判定对象数组* @return*/public static boolean isNullOrEmpty(Object[] obj) {if (obj == null || obj.length == 0) {return true;} else {return false;}}/**** @description 对于Collection类型的非空判断** @param collection 被判定Collection类型对象* @return*/public static boolean isNullOrEmpty(Collection collection) {if (collection == null || collection.isEmpty()) {return true;} else {return false;}}/*** @方法名:对于Map类型的非空判断* @功能说明:对于Map类型的非空判断* @return boolean true-为空,false-不为空* @throws*/@SuppressWarnings("rawtypes")public static boolean isNullOrEmpty( Map map) {if (map == null || map.isEmpty()) {return true;} else {return false;}}/**** @方法名:removeNullUnit* @功能说明: 删除集合中的空元素* @return*/public static <T> List<T> removeNullUnit(List<T> xllxList) {List<T> need = new ArrayList<T>();for (int i = 0; i < xllxList.size(); i++) {if (!isNullOrEmpty(xllxList.get(i))) {need.add(xllxList.get(i));}}return need;}}

使用的关键依赖(除Spring框架外):

        <dependency><groupId>org.influxdb</groupId><artifactId>influxdb-java</artifactId><version>2.18</version></dependency><!--orika 拷贝工具 --><dependency><groupId>ma.glasnost.orika</groupId><artifactId>orika-core</artifactId><version>1.5.4</version></dependency><!--        切面--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId></dependency>

5_使用

经过上面的一系列封装,我们就可以使用类似mybatis注解的方式操作influxDB了。

我们来看下他在业务mapper中的使用:

java">import org.apache.ibatis.annotations.Mapper;
import org.example.influxDd.InfluxDBBaseMapper;
import org.example.influxDd.anno.Param;
import org.example.influxDd.anno.Select;import java.util.List;/*** BusinessLogMapper** @describe: 数据埋点日志持久层(influxDB)* @date: 2024/10/8 20:10*/
@Mapper
public interface BusinessLogMapper extends InfluxDBBaseMapper {/*** 每日新注册用户* @param begin yyyy-MM-dd HH:mm:ss* @param end yyyy-MM-dd HH:mm:ss* @return*/@Select(value = "SELECT * FROM log WHERE response_code = '200' and  time > #{begin} and time < #{end} and request_uri =~/register-user/",resultType = BusinessLog.class,database = "point_data")List<BusinessLog> dnu(@Param("begin")String begin, @Param("end")String end);}

Mock 的实体类对象

java">import lombok.Data;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Measurement;/*** BusinessLog.java* @describe: 数据埋点实体类--入库时间序列数据库*/
@Data
@Measurement(database = "point_data", name = "log")
public class BusinessLog {@Column(name = "request_id")public String requestId;@Column(name = "host")public String host;@Column(name = "host_address")public String hostAddress;@Column(name = "request_uri", tag = true)public String requestUri;@Column(name = "request_method", tag = true)public String requestMethod;@Column(name = "request_body")public String requestBody;@Column(name = "response_body")public String responseBody;@Column(name = "response_code", tag = true)public String responseCode;@Column(name = "response_msg")public String responseMsg;@Column(name = "user_id")public String userId;@Column(name = "user_name")public String userName;@Column(name = "business_type")public String businessType;@Column(name = "device_number")public String deviceNumber;@Column(name = "company_no")public String companyNO;@Column(name = "sex")public String sex;@Column(name = "create_by")public Long createBy;@Column(name = "update_by")public Long updateBy;@Column(name = "data_state", tag = true)public String dataState ="0";@Column(name = "province")public String province;@Column(name = "city")public String city;}

测试

java">package org.example;import org.example.entity.BusinessLog;
import org.example.mapper.BusinessLogMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;/*** @author shenyang* @version 1.0* @info all* @since 2024/10/12 23:25*/
@SpringBootTest
public class Test22 {@Resourceprivate BusinessLogMapper businessLogMapper;@Testpublic void test() {BusinessLog businessLog = new BusinessLog();businessLog.setRequestId("RequestId");businessLog.setHost("Host");businessLog.setHostAddress("HostAddress");businessLog.setRequestUri("RequestUri");businessLog.setRequestMethod("setRequestMethod");businessLog.setRequestBody("setRequestBody");businessLog.setResponseBody("setResponseBody");businessLog.setResponseCode("setResponseCode");businessLog.setResponseMsg("setResponseMsg");businessLog.setUserId("setUserId");businessLog.setUserName("setUserName");businessLog.setBusinessType("setBusinessType");businessLog.setDeviceNumber("setDeviceNumber");businessLog.setCompanyNO("setCompanyNO");businessLog.setSex("setSex");businessLog.setCreateBy(0L);businessLog.setUpdateBy(0L);businessLog.setDataState("setDataState");businessLog.setProvince("setProvince");businessLog.setCity("setCity");businessLogMapper.insertOne(businessLog);List<BusinessLog> dnu = businessLogMapper.dnu(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.of(2023, 12, 22, 00, 00)), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.of(2024, 12, 22, 00, 00)));System.out.println(dnu);}
}

6_总结

注意:本封装组件适用于1.X对于2.X由于认证方式的改变不能被正确兼容。


http://www.ppmy.cn/embedded/127233.html

相关文章

工程师 - 版本管理工具从CVS到SVN的演变

CVS - Concurrent Versions System CVS&#xff08;Concurrent Versions System&#xff0c;并发版本系统&#xff09;在软件开发早期曾被广泛用作版本控制系统&#xff0c;但后来由于多种原因而过时&#xff0c;并被 SVN&#xff08;Subversion&#xff09;等更新的系统所取代…

3.6.xx版本SpringBoot创建基于Swagger接口文档

介绍 基于Swagger构建的JavaAPI文档工具&#xff0c;实现后端功能的测试&#xff0c;并撰写API接口文档。 方法 pom.xml中引入依赖,要注意的是&#xff0c;本依赖使用的SpringBoot版本为3.6.xx <!--Knife4j--><dependency><groupId>com.github.xiaoymin<…

2014年国赛高教杯数学建模C题生猪养殖场的经营管理解题全过程文档及程序

2014年国赛高教杯数学建模 C题 生猪养殖场的经营管理 某养猪场最多能养10000头猪&#xff0c;该养猪场利用自己的种猪进行繁育。养猪的一般过程是&#xff1a;母猪配种后怀孕约114天产下乳猪&#xff0c;经过哺乳期后乳猪成为小猪。小猪的一部分将被选为种猪&#xff08;其中公…

安卓13禁止用户打开开发者选项 android13禁止用户打开开发者选项

总纲 android13 rom 开发总纲说明 文章目录 1.前言2.问题分析3.代码分析4.代码修改5.编译6.彩蛋1.前言 设置 =》关于平板电脑 =》版本号,一般的话,在这里连续点击就可以打开我们的开发者选项了。但是有些系统要进行保密,因此要禁止用户进入。 2.问题分析 这里我们是通过点…

每日一题学习笔记

问题描述 为了修复黄金律法&#xff0c;MaverickFW 收集了传说中的武器和传说中的魔法。MaverickFW 的武器槽和魔法槽都有 N 个&#xff0c;但是在战斗中同时切换武器和魔法太痛苦了。为了简化操作&#xff0c;MaverickFW 决定重新排列 N 个武器或者魔法使得冲突最小。我们设定…

OmniPlan Pro for Mac 项目管理流程软件安装教程【保姆级教程,简单小白轻松上手】

Mac分享吧 文章目录 OmniPlan Pro 项目管理流程软件 安装完成&#xff0c;软件打开效果一、Mac中安装OmniPlan Pro 项目管理流程软件——v4.91️⃣&#xff1a;下载软件2️⃣&#xff1a;安装软件&#xff0c;将安装包从左侧拖入右侧文件夹中&#xff0c;并等待安装完成3️⃣&…

【60天备战2024年11月软考高级系统架构设计师——第40天:性能优化与高可用设计(总结)】

性能优化和高可用性是现代云架构设计的核心目标。通过合理的策略和设计模式&#xff0c;架构师可以确保系统在高负载情况下仍能快速响应&#xff0c;并且在故障情况下保持服务的持续可用性。理解这些原则和策略&#xff0c;对于构建高性能、高可用的云应用至关重要。 关键策略…

如何解决 Open /etc/postfix/main.cf: Permission denied ?

最近我的 Postfix 邮件系统无法发送电子邮件&#xff0c;报错内容&#xff1a;Open /etc/postfix/main.cf: Permission denied 经过一番调查&#xff0c;我能够解决这个问题。 日志文件中发现的错误如下&#xff1a; Jun 27 12:51:02 tecadmin postfix/postfix-script[11764]…