Commit e7db7235 authored by huangcb's avatar huangcb

Init

parents
*.class
*.iml
*.log
/*.iml
/.idea/
/log/
/logs/
*/target/
/target/
#!/bin/bash
#这里可替换为你自己的执行程序,其他代码无需更改
APP_NAME=datacenter-iot-service.jar
#日志文件,与logback-spring.xml的日志文件保持一致
LOG_FILE=./logs/datacenter-iot-service.log
#日志配置文件
LOG_CONFIG_FILE=./logback-spring.xml
#使用说明,用来提示输入参数
usage() {
echo "Usage: sh 脚本名.sh [start|stop|restart|status]"
exit 1
}
#检查程序是否在运行
is_exist(){
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
#如果不存在返回1,存在返回0
if [ -z "${pid}" ]; then
return 1
else
return 0
fi
}
#启动方法
start(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is already running. pid=${pid} ."
else
nohup java -Xmx128m -Xms128m -Dlogging.config=$LOG_CONFIG_FILE -jar $APP_NAME >> /dev/null 2>&1 &
date
tail -f $LOG_FILE
fi
}
#停止方法
stop(){
is_exist
if [ $? -eq "0" ]; then
kill -9 $pid
else
echo "${APP_NAME} is not running"
fi
}
#输出运行状态
status(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is NOT running."
fi
}
#重启
restart(){
stop
start
}
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage
;;
esac
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<groupId>com.esv.datacenter</groupId>
<artifactId>datacenter-iot-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>datacenter-iot-service</name>
<description>datacenter-iot-service</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
<alibaba-nacos-discovery.version>2.1.1.RELEASE</alibaba-nacos-discovery.version>
<alibaba-nacos-config.version>2.1.1.RELEASE</alibaba-nacos-config.version>
<alibaba-fastjson.version>1.2.62</alibaba-fastjson.version>
<alibaba-druid.version>1.1.22</alibaba-druid.version>
<apache-commons-lang3.version>3.7</apache-commons-lang3.version>
<mybatisplus.version>3.3.1</mybatisplus.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>${alibaba-nacos-discovery.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>${alibaba-nacos-config.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--lettuce pool连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${alibaba-fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${alibaba-druid.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
<profile>
<id>develop</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>*.yml</exclude>
<exclude>application*.properties</exclude>
<exclude>bootstrap.properties</exclude>
<exclude>logback-spring.xml</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</profile>
</profiles>
<build>
<finalName>datacenter-iot-service</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>woff</nonFilteredFileExtension>
<nonFilteredFileExtension>woff2</nonFilteredFileExtension>
<nonFilteredFileExtension>eot</nonFilteredFileExtension>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
<nonFilteredFileExtension>svg</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.esv.datacenter.iot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextListener;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
/**
* @description: 启动类
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/07 15:17
* @version:1.0
*/
@SpringBootApplication
@EnableDiscoveryClient
public class BaseApplication {
public static void main(String[] args) {
SpringApplication.run(BaseApplication.class, args);
}
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
@PostConstruct
void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
}
}
package com.esv.datacenter.iot.common.component;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* @description:
* @project: htwl-base-service
* @name: com.esv.htwl.base.common.component.ApplicationLoadRunner
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/28 14:33
* @version:1.0
*/
@Slf4j
@Component
public class ApplicationLoadRunner implements ApplicationRunner {
@Value("${spring.application.name}")
private String applicationName;
@Override
public void run(ApplicationArguments var) {
log.info("-------------------- [{}]初始化完成 --------------------", applicationName);
}
}
\ No newline at end of file
package com.esv.datacenter.iot.common.constants;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.common.constants.CommonConstants
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/26 19:08
* @version:1.0
*/
public class CommonConstants {
/**
* 访问端来源:1-浏览器端、2-Android端、3-iOS端、4-后台服务端
**/
public static final String REQ_SOURCE_TYPE_KEY = "Source-Type";
public static final String REQ_SOURCE_TYPE_WEB = "1";
public static final String REQ_SOURCE_TYPE_ANDROID = "2";
public static final String REQ_SOURCE_TYPE_IOS = "3";
public static final String REQ_SOURCE_TYPE_SERVICE = "4";
/**
* Feign调用返回参数
**/
public static final String FEIGN_RESULT_CODE = "code";
public static final String FEIGN_RESULT_MESSAGE = "message";
public static final String FEIGN_RESULT_DATA = "data";
public static final int FEIGN_RESULT_SUCCESS = 200;
/**
* 日志ID
**/
public static final String LOG_TRACE_ID = "traceId";
/**
* 字符串"null"
**/
public static final String NULL_STRING = "null";
/**
* 字符串"unknown"
**/
public static final String UNKNOWN_STRING = "unknown";
/**
* 默认字符编码
**/
public static final String DEFAULT_CHARACTER_ENCODING = "utf-8";
/**
* Http请求方式
**/
public static final String HTTP_REQUEST_METHOD_GET = "GET";
public static final String HTTP_REQUEST_METHOD_POST = "POST";
/**
* Http请求头
**/
public static final String HTTP_HEADER_X_FORWARDED_FOR = "x-forwarded-for";
public static final String HTTP_HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
public static final String HTTP_HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
}
package com.esv.datacenter.iot.common.em;
/**
* @description: DB记录是否删除标识
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.constants.DbDeletedEnum
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/13 15:08
* @version:1.0
*/
public enum DbDeletedEnum {
NO(false, "未删除"),
YES(true, "已删除");
private Boolean code;
private String message;
DbDeletedEnum(Boolean code, String message) {
this.code = code;
this.message = message;
}
public Boolean getCode() {
return code;
}
public void setCode(Boolean code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.esv.datacenter.iot.common.exception;
/**
* @description: 自定义业务异常
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.exception.EException
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:21
* @version:1.0
*/
public class EException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int code = 500;
private String message;
public EException(String message) {
super(message);
this.message = message;
}
public EException(String message, Throwable e) {
super(message, e);
this.message = message;
}
public EException(int code, String message) {
super(message);
this.code = code;
this.message = message;
}
public EException(int code, String message, Throwable e) {
super(message, e);
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.esv.datacenter.iot.common.filter;
import com.esv.datacenter.iot.common.response.EResponse;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* @description: 权限过滤器
* @project: freight-base-service
* @name: com.esv.htwl.base.common.filter.AuthFilter
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/23 16:24
* @version:1.0
*/
@Slf4j
public class AuthFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// HttpServletRequest request = (HttpServletRequest) servletRequest;
// HttpServletResponse response = (HttpServletResponse) servletResponse;
// String accessToken = request.getHeader("Union-Authorization");
// if (StringUtils.isBlank(accessToken)) {
// this.errorResponse(EResponse.error(ECode.TOKEN_INVALID), response);
// return;
// } else {
// // 解析并校验Token
// }
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
private void errorResponse(EResponse eResponse, HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
OutputStreamWriter osw = null;
PrintWriter writer = null;
try {
osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
writer = new PrintWriter(osw, true);
writer.write(eResponse.toString());
writer.flush();
osw.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (null != writer) {
writer.close();
}
if (null != osw) {
try {
osw.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
}
package com.esv.datacenter.iot.common.filter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;
/**
* @description: 处理Logback traceId过滤器
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.filter.LogbackFilter
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/13 11:35
* @version:1.0
*/
@Slf4j
public class LogbackFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 获取来自上游服务的传参traceId
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String traceId = httpServletRequest.getHeader("gateway_traceid");
if (StringUtils.isBlank(traceId)) {
traceId = httpServletRequest.getHeader("trace_id");
}
boolean bInsertMDC = setMDC(traceId);
try {
filterChain.doFilter(servletRequest, servletResponse);
} finally {
if(bInsertMDC) {
MDC.remove("traceId");
}
}
}
@Override
public void destroy() {
}
private boolean setMDC(String traceId) {
if (StringUtils.isEmpty(traceId) || "null".equalsIgnoreCase(traceId)) {
traceId = UUID.randomUUID().toString().replace("-", "");
}
MDC.put("traceId", traceId);
return true;
}
}
package com.esv.datacenter.iot.common.filter;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.iot.common.util.ReqUtils;
import com.esv.datacenter.iot.common.constants.CommonConstants;
import com.esv.datacenter.iot.common.wrapper.RestRequestWrapper;
import com.esv.datacenter.iot.common.wrapper.RestResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @description: Rest请求日志Filter
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.web.filter.RestLogFilter
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/09 17:44
* @version:1.0
*/
@Slf4j
public class RestLogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
RestRequestWrapper requestWrapper = new RestRequestWrapper((HttpServletRequest)servletRequest);
RestResponseWrapper responseWrapper = new RestResponseWrapper((HttpServletResponse) servletResponse);
// 日志输出请求体
this.logReq(requestWrapper);
// 日志输出请求头
this.logReqHeader(requestWrapper);
filterChain.doFilter(requestWrapper, responseWrapper);
// 日志输出返回体
this.logRes(responseWrapper);
}
/**
* 获取请求返回体
**/
private String getPostBodyStr(HttpServletRequest request) {
String bodyStr = null;
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = request.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(CommonConstants.DEFAULT_CHARACTER_ENCODING)));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
if (0 == sb.length()) {
Map<String, String> bodyMap = new HashMap<>();
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
for (String value : entry.getValue()) {
bodyMap.put(entry.getKey(), value);
}
}
bodyStr = bodyMap.toString();
} else {
bodyStr = sb.toString();
}
} catch (IOException e) {
log.error("解析post参数时发生错误:{}", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bodyStr;
}
/**
* 日志输出请求体
**/
private void logReq(RestRequestWrapper requestWrapper) {
String url = requestWrapper.getRequestURI();
String method = requestWrapper.getMethod();
String reqBody = "";
// 获取get、post请求体
if (CommonConstants.HTTP_REQUEST_METHOD_GET.equalsIgnoreCase(method)) {
Enumeration em = requestWrapper.getParameterNames();
while (em.hasMoreElements()) {
String k = em.nextElement().toString();
String v = requestWrapper.getParameter(k);
reqBody += "&" + k + "=" + v;
}
reqBody = reqBody.replaceFirst("&", "");
} else if (CommonConstants.HTTP_REQUEST_METHOD_POST.equalsIgnoreCase(method)) {
reqBody = this.getPostBodyStr(requestWrapper);
}
// 日志输出请求体
log.info("[IP={}]收到{}请求,url:{},body:{}", ReqUtils.getHttpClientIp(requestWrapper), method, url, reqBody);
}
/**
* 日志输出请求头
**/
private void logReqHeader(RestRequestWrapper request) {
JSONObject headerJson = new JSONObject();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
headerJson.put(key, request.getHeader(key));
}
log.info("请求头:{}", headerJson.toJSONString());
}
/**
* 日志输出返回体
**/
private void logRes(RestResponseWrapper responseWrapper) {
byte[] bytes = responseWrapper.getBody();
String resBody = null;
try {
resBody = new String(bytes, CommonConstants.DEFAULT_CHARACTER_ENCODING);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
log.info("请求响应:{}", resBody);
}
}
\ No newline at end of file
package com.esv.datacenter.iot.common.handler;
import com.esv.datacenter.iot.common.exception.EException;
import com.esv.datacenter.iot.common.response.ECode;
import com.esv.datacenter.iot.common.response.EResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;
/**
* @description:
* @project: SpringCloudTemplate
* @name: com.esv.htwl.base.common.handler.RestExceptionHandler
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:41
* @version:1.0
*/
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(value = Exception.class)
public EResponse defaultErrorHandler(HttpServletRequest req, Exception e) {
EResponse r;
if (e instanceof EException) {
r = EResponse.error(((EException) e).getCode(), e.getMessage());
} else if (e instanceof MethodArgumentNotValidException) {
String message = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("|"));
r = EResponse.error(ECode.PARAM_ERROR.code(), ECode.PARAM_ERROR.message() + "[" + message + "]");
} else if (e instanceof ConstraintViolationException) {
String message = e.getMessage();
if (message.contains(":")) {
message = message.split(":")[1];
}
r = EResponse.error(ECode.PARAM_ERROR.code(), ECode.PARAM_ERROR.message() + "[" + message + "]");
} else if (e instanceof MissingServletRequestParameterException || e instanceof HttpMessageNotReadableException) {
r = EResponse.error(ECode.PARAM_ERROR.code(), ECode.PARAM_ERROR.message() + "[" + e.getMessage() + "]");
} else {
r = EResponse.error(ECode.SERVER_ERROR);
log.error(e.getMessage(), e);
}
return r;
}
}
package com.esv.datacenter.iot.common.response;
/**
* @description: 系统响应码
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.response.ECode
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:34
* @version:1.0
*/
public class ECode {
public static final ECode SUCCESS = new ECode(200, "success");
public static final ECode ACCESS_DENIED = new ECode(401, "没有访问权限");
public static final ECode SERVER_ERROR = new ECode(500, "服务内部错误");
public static final ECode SERVICE_UNAVAILABLE = new ECode(503, "服务限流,暂不可用");
public static final ECode PARAM_ERROR = new ECode(600, "参数不合法");
public static final ECode TOKEN_INVALID = new ECode(601, "无效的Token");
public static final ECode TOKEN_EXPIRED = new ECode(602, "Token已过期");
public static final ECode BATCHID_FORMATTOR_ERROR = new ECode(11001, "时间格式错误");
public static final ECode BATCHID_LENTGH_ERROR = new ECode(11001, "长度错误");
public ECode(int code, String message) {
this.code = code;
this.message = message;
}
private int code;
private String message;
public int code() {
return code;
}
public String message() {
return message;
}
}
package com.esv.datacenter.iot.common.response;
import com.esv.datacenter.iot.common.util.LogUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
/**
* @description: Rest请求统一返回对象
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.response.EResponse
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:23
* @version:1.0
*/
public class EResponse<T> implements Serializable {
private static final long serialVersionUID = 6472520481853704969L;
private int code;
private String message;
private long responseTime;
private String logId;
private T data;
private EResponse() {
this.responseTime = System.currentTimeMillis();
this.logId = LogUtils.getThreadTraceId();
}
private EResponse(int code, String message) {
this();
this.code = code;
this.message = message;
}
private EResponse(int code, String message, T data) {
this();
this.code = code;
this.message = message;
this.data = data;
}
private EResponse(ECode eCode) {
this(eCode.code(), eCode.message());
}
private EResponse(T data) {
this(ECode.SUCCESS);
this.data = data;
}
/**
* description 成功返回
* param []
* return com.esv.common.response.EResponse
* author chenfm
* createTime 2020/3/6 14:50
**/
public static EResponse ok() {
return new EResponse(ECode.SUCCESS);
}
/**
* description 成功返回(带数据)
* param [data] 返回数据
* return com.esv.common.response.EResponse<T>
* author chenfm
* createTime 2020/3/6 14:50
**/
public static<T> EResponse<T> ok(T data) {
return new EResponse<T>(data);
}
/**
* description 返回默认系统异常
* param []
* return com.esv.springcloud.template.common.response.EResponse
* author Administrator
* createTime 2020/03/13 15:36
**/
public static EResponse error() {
return error(ECode.SERVER_ERROR);
}
/**
* description 返回自定义code、message异常
* param []
* return com.esv.common.response.EResponse
* author chenfm
* createTime 2020/3/9 13:32
*
* @param code
* @param message*/
public static EResponse error(int code, String message) {
return new EResponse(code, message);
}
/**
* description 返回自定义code、message、data异常
* param [code, message, data]
* return com.esv.htwl.customer.common.response.EResponse<T>
* author HuangChaobin
* createTime 2020/07/09 15:04
**/
public static<T> EResponse<T> error(int code, String message, T data) {
return new EResponse(code, message, data);
}
/**
* description 异常返回
* param [rCode] 异常码
* return com.esv.common.response.EResponse
* author chenfm
* createTime 2020/3/6 14:50
**/
public static EResponse error(ECode eCode) {
return new EResponse(eCode);
}
/**
* description 判断返回是否成功
* param []
* return boolean
* author chenfm
* createTime 2020/3/6 14:51
**/
public boolean success() {
return this.code == ECode.SUCCESS.code();
}
/**
* description 修改提示信息
* param [message] 提示信息
* return void
* author chenfm
* createTime 2020/3/6 17:44
**/
public EResponse message(String message) {
this.message = message;
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public long getResponseTime() {
return responseTime;
}
public void setResponseTime(long responseTime) {
this.responseTime = responseTime;
}
public String getLogId() {
return logId;
}
public void setLogId(String logId) {
this.logId = logId;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
\ No newline at end of file
package com.esv.datacenter.iot.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
/**
* @description: 对称加密AES工具类
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.util.AESSecretUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/13 14:29
* @version:1.0
*/
@Slf4j
public class AESSecretUtils {
/**秘钥的大小*/
private static final int KEYSIZE = 128;
/**
* @Author: Helon
* @Description: AES加密
* @param data - 待加密内容
* @param key - 加密秘钥
* @Data: 2018/7/28 18:42
* @Modified By:
*/
public static byte[] encrypt(String data, String key) {
if (StringUtils.isNotBlank(data)) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
//选择一种固定算法,为了避免不同java实现的不同算法,生成不同的密钥,而导致解密失败
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes());
keyGenerator.init(KEYSIZE, random);
SecretKey secretKey = keyGenerator.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
byte[] byteContent = data.getBytes("utf-8");
// 初始化
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 加密
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (Exception e) {
log.error("AES加密字符串失败", e.getMessage());
}
}
return null;
}
/**
* @Author: Helon
* @Description: AES加密,返回String
* @param data - 待加密内容
* @param key - 加密秘钥
* @Data: 2018/7/28 18:59
* @Modified By:
*/
public static String encryptToStr(String data, String key) {
if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
return null;
} else {
byte[] bytes = encrypt(data, key);
if (null == bytes || 0 == bytes.length) {
return null;
} else {
return parseByte2HexStr(bytes);
}
}
}
/**
* @Author: Helon
* @Description: AES解密
* @param data - 待解密字节数组
* @param key - 秘钥
* @Data: 2018/7/28 19:01
* @Modified By:
*/
public static byte[] decrypt(byte[] data, String key) {
if (ArrayUtils.isNotEmpty(data)) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
//选择一种固定算法,为了避免不同java实现的不同算法,生成不同的密钥,而导致解密失败
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes());
keyGenerator.init(KEYSIZE, random);
SecretKey secretKey = keyGenerator.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] result = cipher.doFinal(data);
// 加密
return result;
} catch (Exception e) {
log.error("AES解密字符串失败", e.getMessage());
}
}
return null;
}
/**
* @Author: Helon
* @Description: AES解密,返回String
* @param enCryptdata - 待解密字节数组
* @param key - 秘钥
* @Data: 2018/7/28 19:01
* @Modified By:
*/
public static String decryptToStr(String enCryptdata, String key) {
if (StringUtils.isEmpty(enCryptdata)) {
return null;
}
byte[] decryptBytes = decrypt(parseHexStr2Byte(enCryptdata), key);
if (null == decryptBytes) {
return null;
}
return new String(decryptBytes);
}
/**
* @Author: Helon
* @Description: 将二进制转换成16进制
* @param buf - 二进制数组
* @Data: 2018/7/28 19:12
* @Modified By:
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* @Author: Helon
* @Description: 将16进制转换为二进制
* @param hexStr - 16进制字符串
* @Data: 2018/7/28 19:13
* @Modified By:
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
package com.esv.datacenter.iot.common.util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* @description: 图片验证码工具类
* @project: base-service
* @name: com.esv.htwl.base.common.util.CaptchaUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 14:18
* @version:1.0
*/
public class CaptchaUtils {
/**
* 验证码字符集
**/
private static final char[] chars = {
'2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
/**
* 字符数量
**/
private static final int SIZE = 4;
/**
* 干扰线数量
**/
private static final int LINES = 5;
/**
* 宽度
**/
private static final int WIDTH = 80;
/**
* 高度
**/
private static final int HEIGHT = 30;
/**
* 字体大小
**/
private static final int FONT_SIZE = 30;
/**
* description 创建图片验证码
* param []
* return java.lang.Object[]
* author Administrator
* createTime 2020/04/11 14:14
**/
public static Object[] createCaptchaImage() {
StringBuffer sb = new StringBuffer();
// 1.创建空白图片
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.获取图片画笔
Graphics graphic = image.getGraphics();
// 3.设置画笔颜色
graphic.setColor(Color.LIGHT_GRAY);
// 4.绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 5.画随机字符
Random ran = new Random();
for (int i = 0; i <SIZE; i++) {
// 取随机字符索引
int n = ran.nextInt(chars.length);
// 设置随机颜色
graphic.setColor(getRandomColor());
// 设置字体大小
graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 画字符
graphic.drawString(chars[n] + "", i * WIDTH / SIZE, HEIGHT * 4 / 5);
// 记录字符
sb.append(chars[n]);
}
// 6.画干扰线
/* for (int i = 0; i < LINES; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}*/
graphic.dispose();
// 7.返回验证码和图片
return new Object[]{sb.toString(), image};
}
/**
* description 获取随机颜色
* param []
* return java.awt.Color
* author Administrator
* createTime 2020/04/11 14:12
**/
private static Color getRandomColor() {
Random random = new Random();
Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
return color;
}
}
package com.esv.datacenter.iot.common.util;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
/**
* @description: 日期工具类
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.util.DateUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 18:02
* @version:1.0
*/
public class DateUtils {
public static final String DATE_FORMAT0 = "yyyy-MM-dd HH:mm:ss:SSS";
public static final String DATE_FORMAT1 = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT2 = "yyyyMMdd";
public static final String DATE_FORMAT3 = "yyyy-MM-dd";
public static final String DATE_FORMAT4 = "yyyyMMddHHmmss";
public static final String DATE_FORMAT5 = "yyyy-MM";
public static final String DATE_FORMAT6 = "yyyyMMddHHmmssSSS";
public static final String DATE_FORMAT7 = "MMdd";
public static final String DATE_FORMAT8 = "mm HH";
public static final String DATE_FORMAT9 = "HH:mm:ss";
/**
* 一个月的时间换算成秒:30 * 24 * 60 * 60
*/
public static final long MONTH_TO_SECONDS = 2592000L;
/**
* 一天的时间换算成秒:24 * 60 * 60
*/
public static final long DAY_TO_SECONDS = 86400L;
/**
* 获取当前Date类型时间
* @return
*/
public static Date getSysdate() {
return new Date();
}
/**
* 获取当前String(yyyy-MM-dd HH:mm:ss)类型时间
* @return
*/
public static String getSysdateStr() {
Date date = new Date();
return format(date, DATE_FORMAT1);
}
/**
* 获取当前String(yyyyMMddHHmmssSSS)类型时间
* @return
*/
public static String getSysdateStr19() {
Date date = new Date();
return format(date, DATE_FORMAT6);
}
/**
* 获取指定字符串格式的当前时间
* @param format
* @return
*/
public static String getSysdateStr(String format) {
Date date = new Date();
return format(date, format);
}
/**
* 格式化日期,格式为“yyyy-MM-dd HH:mm:ss”
* @param date
* @return
*/
public static String format(Date date) {
return format(date, DateUtils.DATE_FORMAT1);
}
/**
* 格式化日期,格式自定义
* @param date
* @param format
* @return
*/
public static String format(Date date, String format) {
if (date == null) {
return null;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(format);
}
/**
* 字符串转换成日期,字符串格式同date类型
* @param dateStr
* @param format
* @return
*/
public static Date parse(String dateStr, String format) {
if (null == dateStr) {
return null;
}
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(format);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateStr);
return dateTime.toDate();
}
/**
* 字符串转换成日期
* @param dateStr
* @return
*/
public static Date parse(String dateStr) {
if (-1 < dateStr.indexOf("-")) {
return parse(dateStr, "yyyy-MM-dd");
} else if (-1 < dateStr.indexOf("/")) {
return parse(dateStr, "yyyy/MM/dd");
} else {
return parse(dateStr, "yyyyMMdd");
}
}
/**
* 判断date日期是否过期(与当前时刻比较)
*
* @param date
* @return
*/
public static boolean isTimeExpired(Date date) {
if (null == date) {
return true;
}
String timeStr = format(date);
return isBeforeNow(timeStr);
}
/**
* 判断date日期是否过期(与当前时刻比较)
*
* @param timeStr
* @return
*/
public static boolean isTimeExpired(String timeStr) {
if (StringUtils.isBlank(timeStr)) {
return true;
}
return isBeforeNow(timeStr);
}
/**
* 判断timeStr是否在当前时刻之前
*
* @param timeStr
* @return
*/
private static boolean isBeforeNow(String timeStr) {
DateTimeFormatter format = DateTimeFormat.forPattern(DATE_FORMAT1);
DateTime dateTime = DateTime.parse(timeStr, format);
return dateTime.isBeforeNow();
}
/**
* 日期加天数
*
* @param date
* @param days
* @return
*/
public static Date plusDays(Date date, Integer days) {
return plusOrMinusDays(date, days, 0);
}
/**
* 日期减天数
*
* @param date
* @param days
* @return
*/
public static Date minusDays(Date date, Integer days) {
return plusOrMinusDays(date, days, 1);
}
/**
* 加减天数
*
* @param date
* @param days
* @param type 0:加天数 1:减天数
* @return
*/
private static Date plusOrMinusDays(Date date, Integer days, Integer type) {
if (null == date) {
return null;
}
days = null == days ? 0 : days;
DateTime dateTime = new DateTime(date);
if (type == 0) {
dateTime = dateTime.plusDays(days);
} else {
dateTime = dateTime.minusDays(days);
}
return dateTime.toDate();
}
/**
* 日期加分钟
*
* @param date
* @param minutes
* @return
*/
public static Date plusMinutes(Date date, Integer minutes) {
return plusOrMinusMinutes(date, minutes, 0);
}
/**
* 日期减分钟
*
* @param date
* @param minutes
* @return
*/
public static Date minusMinutes(Date date, Integer minutes) {
return plusOrMinusMinutes(date, minutes, 1);
}
/**
* 加减分钟
*
* @param date
* @param minutes
* @param type 0:加分钟 1:减分钟
* @return
*/
private static Date plusOrMinusMinutes(Date date, Integer minutes, Integer type) {
if (null == date) {
return null;
}
minutes = null == minutes ? 0 : minutes;
DateTime dateTime = new DateTime(date);
if (type == 0) {
dateTime = dateTime.plusMinutes(minutes);
} else {
dateTime = dateTime.minusMinutes(minutes);
}
return dateTime.toDate();
}
/**
* 日期加月份
*
* @param date
* @param months
* @return
*/
public static Date plusMonths(Date date, Integer months) {
return plusOrMinusMonths(date, months, 0);
}
/**
* 日期减月份
*
* @param date
* @param months
* @return
*/
public static Date minusMonths(Date date, Integer months) {
return plusOrMinusMonths(date, months, 1);
}
/**
* 加减月份
*
* @param date
* @param months
* @param type 0:加月份 1:减月份
* @return
*/
private static Date plusOrMinusMonths(Date date, Integer months, Integer type) {
if (null == date) {
return null;
}
months = null == months ? 0 : months;
DateTime dateTime = new DateTime(date);
if (type == 0) {
dateTime = dateTime.plusMonths(months);
} else {
dateTime = dateTime.minusMonths(months);
}
return dateTime.toDate();
}
/**
* 判断target是否在开始和结束时间之间
*
* @param target
* @param startTime
* @param endTime
* @return
*/
public static boolean isBetweenStartAndEndTime(Date target, Date startTime, Date endTime) {
if (null == target || null == startTime || null == endTime) {
return false;
}
DateTime dateTime = new DateTime(target);
return dateTime.isAfter(startTime.getTime()) && dateTime.isBefore(endTime.getTime());
}
}
package com.esv.datacenter.iot.common.util;
import com.esv.datacenter.iot.common.constants.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import java.util.UUID;
/**
* @description:
* @author: huangchaobin@esvtek.com
* @createTime: 2020/07/21 18:41
* @version:1.0
*/
public class LogUtils {
/**
* @description 获取当前线程设置日志traceId
* @return String
* @author huangChaobin@esvtek.com
* @createTime 2020/07/21 18:43
**/
public static String getThreadTraceId() {
String traceId = MDC.get(CommonConstants.LOG_TRACE_ID);
if (StringUtils.isBlank(traceId)) {
traceId = UUID.randomUUID().toString().replaceAll("-", "");
}
return traceId;
}
}
package com.esv.datacenter.iot.common.util;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.iot.common.constants.CommonConstants;
import com.esv.datacenter.iot.common.exception.EException;
import com.esv.datacenter.iot.common.response.ECode;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* @description: Http请求工具类
* @project: freight-base-service
* @name: com.esv.htwl.base.common.util.ReqUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/26 19:09
* @version:1.0
*/
public class ReqUtils {
/**
* 获得Http客户端的ip
* @param req
* @return
*/
public static String getHttpClientIp(HttpServletRequest req){
String ip = req.getHeader(CommonConstants.HTTP_HEADER_X_FORWARDED_FOR);
if(ip == null || ip.length() == 0 || CommonConstants.UNKNOWN_STRING.equalsIgnoreCase(ip)) {
ip = req.getHeader(CommonConstants.HTTP_HEADER_PROXY_CLIENT_IP);
}
if(ip == null || ip.length() == 0 || CommonConstants.UNKNOWN_STRING.equalsIgnoreCase(ip)) {
ip = req.getHeader(CommonConstants.HTTP_HEADER_WL_PROXY_CLIENT_IP);
}
if(ip == null || ip.length() == 0 || CommonConstants.UNKNOWN_STRING.equalsIgnoreCase(ip)) {
ip = req.getRemoteAddr();
}
return ip;
}
/**
* description 校验参数不能为空:key存在、value存在且不为空字符串
* param [reqJson, params]
* return void
* author Administrator
* createTime 2020/04/17 17:23
**/
public static void checkParamsNotBlank(JSONObject reqJson, String[] params) throws EException {
for (int i = 0; i < params.length; i++) {
if (StringUtils.isBlank(reqJson.getString(params[i]))) {
throw new EException(ECode.PARAM_ERROR.code(), "参数"+params[i]+"不能为空");
}
}
}
}
package com.esv.datacenter.iot.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:删除记录
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.validator.groups.ValidatorDelete
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:58
* @version:1.0
*/
public interface ValidatorDelete extends Default {
}
package com.esv.datacenter.iot.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 数校验分组:记录详情
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.validator.groups.ValidatorDetail
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:57
* @version:1.0
*/
public interface ValidatorDetail extends Default {
}
package com.esv.datacenter.iot.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:新增记录
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.validator.groups.ValidatorInsert
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:57
* @version:1.0
*/
public interface ValidatorInsert extends Default {
}
package com.esv.datacenter.iot.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:查询列表
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.validator.groups.ValidatorList
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:58
* @version:1.0
*/
public interface ValidatorList extends Default {
}
package com.esv.datacenter.iot.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:更新记录
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.validator.groups.ValidatorUpdate
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:58
* @version:1.0
*/
public interface ValidatorUpdate extends Default {
}
package com.esv.datacenter.iot.common.vo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import java.util.List;
/**
* @description: 分页查询返回结果VO
* @project: htwl-base-service
* @name: com.esv.htwl.base.common.vo.PageResultVO
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/09 10:01
* @version:1.0
*/
@Data
public class PageResultVO {
/**
* 每页记录条数
**/
private Long pageSize;
/**
* 当前页码
**/
private Long pageNum;
/**
* 总记录条数
**/
private Long total;
/**
* 当前页的记录条数
**/
private Long recordSize;
/**
* 数据
**/
private List<?> record;
public PageResultVO(IPage page, List<?> record) {
this.pageSize = page.getSize();
this.pageNum = page.getCurrent();
this.total = page.getTotal();
this.recordSize = Long.parseLong(String.valueOf(page.getRecords().size()));
this.record = record;
}
}
package com.esv.datacenter.iot.common.wrapper;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
/**
* @description: HttpServletRequest包装类
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.wrapper.RestRequestWrapper
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 17:59
* @version:1.0
*/
public class RestRequestWrapper extends HttpServletRequestWrapper {
private byte[] body;
public RestRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
ServletInputStream inputStream = request.getInputStream();
if (null != inputStream) {
body = readBytes(inputStream);
}
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() {
return bais.read();
}
};
}
private String streamToString(InputStream inputStream) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
StringBuilder builder = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
builder.append(output);
}
return builder.toString();
} catch (IOException e) {
throw new RuntimeException("Http 服务调用失败", e);
}
}
private byte[] readBytes(ServletInputStream inputStream) {
return streamToString(inputStream).getBytes(Charset.forName("UTF-8"));
}
public void setBody(String data) {
this.body = data.getBytes(Charset.forName("UTF-8"));
}
}
package com.esv.datacenter.iot.common.wrapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* @description: HttpServletResponse包装类
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.common.wrapper.RestResponseWrapper
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/12 18:00
* @version:1.0
*/
public class RestResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
private HttpServletResponse response;
public RestResponseWrapper(HttpServletResponse response) {
super(response);
this.response = response;
}
public byte[] getBody() {
return byteArrayOutputStream.toByteArray();
}
@Override
public ServletOutputStream getOutputStream() {
return new ServletOutputStreamWrapper(this.byteArrayOutputStream , this.response);
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new OutputStreamWriter(this.byteArrayOutputStream , this.response.getCharacterEncoding()));
}
@Data
@AllArgsConstructor
private static class ServletOutputStreamWrapper extends ServletOutputStream {
private ByteArrayOutputStream outputStream;
private HttpServletResponse response;
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener listener) {
}
@Override
public void write(int b) throws IOException {
this.outputStream.write(b);
}
@Override
public void flush() throws IOException {
if (! this.response.isCommitted()) {
byte[] body = this.outputStream.toByteArray();
ServletOutputStream outputStream = this.response.getOutputStream();
outputStream.write(body);
outputStream.flush();
}
}
}
}
package com.esv.datacenter.iot.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @description: Cache配置类
* @project: htwl-base-service
* @name: com.esv.htwl.base.config.CacheConfig
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/09 9:57
* @version:1.0
*/
@Configuration
@EnableCaching
public class CacheConfig {
@Value("${spring.application.name}")
private String applicationName;
/**
* description 为SpringCache注册缓存管理器
* param [redisConnectionFactory]
* return org.springframework.cache.CacheManager
* author Administrator
* createTime 2020/03/19 14:26
**/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
long timeToLive = 60L;
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// 解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.computePrefixWith(cacheKeyPrefix())
.entryTtl(Duration.ofMinutes(timeToLive))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(config)
.build();
return cacheManager;
}
/**
* @description 设置缓存key的前缀
* @return org.springframework.data.redis.cache.CacheKeyPrefix
* @author huangChaobin@esvtek.com
* @createTime 2020/07/30 19:49
**/
@Bean
public CacheKeyPrefix cacheKeyPrefix() {
return cacheName -> {
StringBuilder sBuilder = new StringBuilder(8);
sBuilder.append(applicationName).append("::");
sBuilder.append(cacheName).append("::");
return sBuilder.toString();
};
}
/**
* RedisTemplate相关配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
package com.esv.datacenter.iot.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* @description: ResponseBody允许序列化结果值为 null 的数据
* @project: htwl-base-service
* @name: com.esv.htwl.base.config.JacksonConfig
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/09 9:43
* @version:1.0
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper() {
return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
}
package com.esv.datacenter.iot.config;
import com.esv.datacenter.iot.common.filter.AuthFilter;
import com.esv.datacenter.iot.common.filter.LogbackFilter;
import com.esv.datacenter.iot.common.filter.RestLogFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description: 注册请求Filter
* @project: SpringCloudTemplate
* @name: com.esv.springcloud.template.web.config.FilterConfig
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/03/09 17:47
* @version:1.0
*/
@Configuration
public class LogFilterConfig {
private static final String URL = "/*";
@Bean
public FilterRegistrationBean<LogbackFilter> logbackFilterRegister() {
FilterRegistrationBean<LogbackFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new LogbackFilter());
registration.addUrlPatterns(URL);
registration.setOrder(Integer.MIN_VALUE);
return registration;
}
@Bean
public FilterRegistrationBean<RestLogFilter> restLogFilterRegister() {
FilterRegistrationBean<RestLogFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new RestLogFilter());
filterRegistrationBean.addUrlPatterns(URL);
filterRegistrationBean.setOrder(Integer.MIN_VALUE + 1);
return filterRegistrationBean;
}
@Bean
public AuthFilter getAuthFilter() {
return new AuthFilter();
}
@Bean
public FilterRegistrationBean<AuthFilter> authFilterRegister() {
FilterRegistrationBean<AuthFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(getAuthFilter());
filterRegistrationBean.addUrlPatterns(URL);
filterRegistrationBean.setOrder(Integer.MIN_VALUE + 2);
return filterRegistrationBean;
}
}
package com.esv.datacenter.iot.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description:
* @project: htwl-base-service
* @name: com.esv.htwl.base.config.MybatisPlusConfig
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/09 9:58
* @version:1.0
*/
@Configuration
@MapperScan({"com.esv.datacenter.iot.*.*.dao"})
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* description MybatisPlus乐观锁插件
* param []
* return com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor
* author chenfm
* createTime 2020/4/13 20:17
**/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
package com.esv.datacenter.iot.module.test.controller;
import com.esv.datacenter.iot.common.response.EResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.test.controller.TestController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/22 14:00
* @version:1.0
*/
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
@GetMapping("/ping")
public EResponse ping() {
return EResponse.ok();
}
}
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.248:3306/data_center?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: data_center
password: 123456
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
redis:
database: 0
host: 192.168.31.248
port: 6379
password:
timeout: 3000
lettuce:
pool:
max-active: 8
max-wait: 3000
max-idle: 8
min-idle: 0
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*Dao.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.esv.datacenter.iot.*.*.entity,com.esv.datacenter.iot.*.*.dto
check-config-location: true
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
global-config:
banner: true
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
logic-delete-value: 1
logic-not-delete-value: 0
management:
endpoints:
web:
exposure:
# "*"开放所有监控端点,指定监控端点,用逗号分隔
include: health,loggers
base-path: /esvActuator
endpoint:
health:
show-details: always
\ No newline at end of file
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.248:3306/data_center?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: data_center
password: 123456
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
redis:
database: 0
host: 192.168.31.248
port: 6379
password:
timeout: 3000
lettuce:
pool:
max-active: 8
max-wait: 3000
max-idle: 8
min-idle: 0
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*Dao.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.esv.datacenter.iot.*.*.entity,com.esv.datacenter.iot.*.*.dto
check-config-location: true
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
global-config:
banner: true
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
logic-delete-value: 1
logic-not-delete-value: 0
management:
endpoints:
web:
exposure:
# "*"开放所有监控端点,指定监控端点,用逗号分隔
include: health,loggers
base-path: /esvActuator
endpoint:
health:
show-details: always
\ No newline at end of file
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.248:3306/data_center?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: data_center
password: 123456
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
redis:
database: 0
host: 192.168.31.248
port: 6379
password:
timeout: 3000
lettuce:
pool:
max-active: 8
max-wait: 3000
max-idle: 8
min-idle: 0
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*Dao.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.esv.datacenter.iot.*.*.entity,com.esv.datacenter.iot.*.*.dto
check-config-location: true
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
global-config:
banner: true
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
logic-delete-value: 1
logic-not-delete-value: 0
management:
endpoints:
web:
exposure:
# "*"开放所有监控端点,指定监控端点,用逗号分隔
include: health,loggers
base-path: /esvActuator
endpoint:
health:
show-details: always
\ No newline at end of file
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.248:3306/data_center?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: data_center
password: 123456
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
redis:
database: 0
host: 192.168.31.248
port: 6379
password:
timeout: 3000
lettuce:
pool:
max-active: 8
max-wait: 3000
max-idle: 8
min-idle: 0
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*Dao.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.esv.datacenter.iot.*.*.entity,com.esv.datacenter.iot.*.*.dto
check-config-location: true
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
global-config:
banner: true
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
logic-delete-value: 1
logic-not-delete-value: 0
management:
endpoints:
web:
exposure:
# "*"开放所有监控端点,指定监控端点,用逗号分隔
include: health,loggers
base-path: /esvActuator
endpoint:
health:
show-details: always
\ No newline at end of file
server:
port: 1010
servlet:
context-path: /iot
nacos:
url: 192.168.31.248:8848
namespace: 1697ea67-be4c-4d38-b00d-39392b9dee8f
group: DEFAULT_GROUP
spring:
application:
name: datacenter-iot-service
profiles:
active: local
main:
allow-bean-definition-overriding: true
cloud:
nacos:
discovery:
server-addr: ${nacos.url}
namespace: ${nacos.namespace}
group: ${nacos.group}
config:
server-addr: ${nacos.url}
namespace: ${nacos.namespace}
group: ${nacos.group}
file-extension: yml
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<springProperty scope="context" name="LOG_FILE_NAME" source="spring.application.name"/>
<!-- 日志存储目录 -->
<property name="LOG_FILE_PATH" value="./logs/" />
<!-- 日志文件大小 -->
<property name="MAX_FILE_SIZE" value="100MB" />
<!-- 日志最大的历史(单位:天) -->
<property name="MAX_HISTORY" value="90" />
<!-- 格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n:换行符-->
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread-%X{traceId}] %-5level %logger{50}.%M[%line]:%msg%n" />
<!-- 控制台输出 -->
<appender name="CONSOLE_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>${LOG_PATTERN}</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
<appender name="FILE_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE_PATH}${LOG_FILE_NAME}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}${LOG_FILE_NAME}-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- mybatis sql日志 日志的级别需要是DEBUG -->
<!-- 日志打印的包的范围,及分类日志文件存储 -->
<logger name="com.esv" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE_APPENDER" />
<appender-ref ref="FILE_APPENDER" />
</logger>
<!--控制台和日志文件输出级别-->
<root level="INFO" additivity="false">
<appender-ref ref="CONSOLE_APPENDER" />
<appender-ref ref="FILE_APPENDER" />
</root>
</configuration>
\ No newline at end of file
package com.esv.datacenter.iot;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @description:
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 14:09
* @version:1.0
*/
@Slf4j
@Data
public class BaseTestController {
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
private static Long TEST_START_TIME;
private static Long TEST_END_TIME;
@Before
public void before() {
log.info("=================================== Test Start ===================================");
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
TEST_START_TIME = System.currentTimeMillis();
}
@After
public void after() {
TEST_END_TIME = System.currentTimeMillis();
log.info("Test耗时:" + (TEST_END_TIME - TEST_START_TIME) + "毫秒");
log.info("=================================== Test End ===================================");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment