Commit a375fce5 authored by huangcb's avatar huangcb

Init

parents
*.class
*.iml
*.log
/*.iml
/.idea/
/log/
/logs/
*/target/
/target/
#!/bin/bash
#这里可替换为你自己的执行程序,其他代码无需更改
APP_NAME=datacenter-base-service.jar
#日志文件,与logback-spring.xml的日志文件保持一致
LOG_FILE=./logs/datacenter-base-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-base-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>datacenter-base-service</name>
<description>datacenter-base-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-base-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.base;
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.base.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.base.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;
/**
* 字符串"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.base.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.base.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.base.common.filter;
import com.esv.datacenter.base.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.base.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.base.common.filter;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.base.common.util.ReqUtils;
import com.esv.datacenter.base.common.constants.CommonConstants;
import com.esv.datacenter.base.common.wrapper.RestRequestWrapper;
import com.esv.datacenter.base.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.base.common.handler;
import com.esv.datacenter.base.common.exception.EException;
import com.esv.datacenter.base.common.response.ECode;
import com.esv.datacenter.base.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.base.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.base.common.response;
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 T data;
private EResponse() {
this.responseTime = System.currentTimeMillis();
}
private EResponse(int code, String message) {
this();
this.code = code;
this.message = message;
}
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 异常返回
* 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 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.base.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.base.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.base.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.base.common.util;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.base.common.constants.CommonConstants;
import com.esv.datacenter.base.common.exception.EException;
import com.esv.datacenter.base.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.base.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.base.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.base.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.base.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.base.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.base.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.base.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.base.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.base.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.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 {
/**
* 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()
.entryTtl(Duration.ofMinutes(timeToLive))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(config)
.build();
return cacheManager;
}
/**
* 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.base.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.base.config;
import com.esv.datacenter.base.common.filter.AuthFilter;
import com.esv.datacenter.base.common.filter.LogbackFilter;
import com.esv.datacenter.base.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.base.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.base.*.*.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.base.module.batch.controller;
import com.esv.datacenter.base.common.response.ECode;
import com.esv.datacenter.base.common.response.EResponse;
import com.esv.datacenter.base.common.util.DateUtils;
import com.esv.datacenter.base.module.batch.form.BatchIdForm;
import com.esv.datacenter.base.module.batch.service.BatchIdService;
import com.esv.datacenter.base.module.batch.vo.BatchIdVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
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.batch.controller.BatchIdController
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:34
* @version: 1.0
*/
@Slf4j
@RestController
@RequestMapping("batchId")
public class BatchIdController {
private BatchIdService batchIdService;
@Autowired
public BatchIdController(BatchIdService batchIdService) {
this.batchIdService = batchIdService;
}
/**
* description 获取批次号
* param [batchIdForm]
* return com.esv.freight.base.common.response.EResponse<com.esv.freight.base.module.batch.vo.BatchIdVO>
* author Administrator
* createTime 2020/05/18 9:42
**/
@PostMapping("generate")
public EResponse<BatchIdVO> generate(@RequestBody @Validated BatchIdForm batchIdForm) {
String formatter = batchIdForm.getFormatter();
String dateStr = DateUtils.getSysdateStr(formatter);
if (formatter.length() != dateStr.length()) {
return EResponse.error(ECode.BATCHID_FORMATTOR_ERROR);
}
if ((batchIdForm.getLength() <= (dateStr.length() + batchIdForm.getPrefix().length()))
|| batchIdForm.getLength() > 30) {
return EResponse.error(ECode.BATCHID_LENTGH_ERROR);
}
batchIdForm.setDateStr(dateStr);
String result;
// 失败重试一次
try {
result = batchIdService.generateBatchId(batchIdForm);
} catch (Exception e) {
result = batchIdService.generateBatchId(batchIdForm);
}
BatchIdVO batchIdVO = new BatchIdVO();
batchIdVO.setBatchId(result);
return EResponse.ok(batchIdVO);
}
}
package com.esv.datacenter.base.module.batch.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.esv.datacenter.base.module.batch.entity.BatchIdEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.batch.dao.BatchIdDao
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:28
* @version: 1.0
*/
@Mapper
public interface BatchIdDao extends BaseMapper<BatchIdEntity> {
/**
* description 查询指定业务的最大计数器
* param [queryObj]
* return com.esv.freight.base.module.batch.entity.BatchIdEntity
* author Administrator
* createTime 2020/05/18 13:15
**/
BatchIdEntity selectMaxCounter(BatchIdEntity queryObj);
}
package com.esv.datacenter.base.module.batch.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
/**
* @description: 批次号
* @project: freight-base-service
* @name: com.esv.htwl.base.module.batch.entity.BatchIdEntity
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:26
* @version: 1.0
*/
@Data
@TableName("base_batch_id_history")
public class BatchIdEntity {
/**
* 主键
**/
private Long id;
/**
* 前缀
**/
private String prefix;
/**
* 日期格式
**/
private String formatter;
/**
* 结果
**/
private String result;
/**
* 长度
**/
private Integer counter;
/**
* 创建时间
**/
private Date createTime;
}
package com.esv.datacenter.base.module.batch.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.batch.form.BatchIdForm
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:34
* @version: 1.0
*/
@Data
public class BatchIdForm {
/**
* 前缀
**/
@Pattern(regexp = "^[a-zA-Z]{1,5}$", message="前缀格式有误")
@NotBlank(message = "前缀不能为空")
private String prefix;
/**
* 日期格式
**/
@Pattern(regexp = "^[y]{2,4}[M]{2}[d]{2}$", message="日期格式有误")
@NotBlank(message = "日期格式不能为空")
private String formatter;
/**
* 长度
**/
@NotNull(message = "长度不能为空")
private Integer length;
private String dateStr;
}
package com.esv.datacenter.base.module.batch.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.datacenter.base.module.batch.entity.BatchIdEntity;
import com.esv.datacenter.base.module.batch.form.BatchIdForm;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.batch.service.BatchIdService
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:31
* @version: 1.0
*/
public interface BatchIdService extends IService<BatchIdEntity> {
/**
* description 生成批次号
* param [batchIdForm]
* return java.lang.String
* author Administrator
* createTime 2020/05/18 9:43
**/
String generateBatchId(BatchIdForm batchIdForm);
}
package com.esv.datacenter.base.module.batch.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.datacenter.base.module.batch.dao.BatchIdDao;
import com.esv.datacenter.base.module.batch.entity.BatchIdEntity;
import com.esv.datacenter.base.module.batch.form.BatchIdForm;
import com.esv.datacenter.base.module.batch.service.BatchIdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.batch.service.impl.BatchIdServiceImpl
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:32
* @version: 1.0
*/
@Service("batchIdService")
public class BatchIdServiceImpl extends ServiceImpl<BatchIdDao, BatchIdEntity> implements BatchIdService {
@Override
public String generateBatchId(BatchIdForm batchIdForm) {
Integer counter;
BatchIdEntity queryObj = new BatchIdEntity();
queryObj.setPrefix(batchIdForm.getPrefix());
queryObj.setFormatter(batchIdForm.getDateStr());
BatchIdEntity record = this.baseMapper.selectMaxCounter(queryObj);
if (null == record) {
counter = 1;
} else {
counter = record.getCounter() + 1;
}
BatchIdEntity batchIdEntity = new BatchIdEntity();
batchIdEntity.setPrefix(batchIdForm.getPrefix());
batchIdEntity.setFormatter(batchIdForm.getDateStr());
batchIdEntity.setCounter(counter);
int length = batchIdForm.getLength() - batchIdForm.getPrefix().length() - batchIdForm.getFormatter().length();
String result = StringUtils.leftPad(String.valueOf(counter), length, "0");
result = batchIdForm.getPrefix() + batchIdForm.getDateStr() + result;
batchIdEntity.setResult(result);
this.baseMapper.insert(batchIdEntity);
return result;
}
}
package com.esv.datacenter.base.module.batch.vo;
import lombok.Data;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.batch.vo.BatchIdVO
* @author: chenfm
* @email: chenfengman@esvtek.com
* @createTime: 2020/4/13 20:37
* @version: 1.0
*/
@Data
public class BatchIdVO {
private String batchId;
}
package com.esv.datacenter.base.module.captcha.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.base.common.response.EResponse;
import com.esv.datacenter.base.module.captcha.form.CaptchaForm;
import com.esv.datacenter.base.module.captcha.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
/**
* @description: 图片验证码Controller
* @project: base-service
* @name: com.esv.htwl.base.module.captcha.controller.CaptchaController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 13:57
* @version:1.0
*/
@Slf4j
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
private CaptchaService captchaService;
@Autowired
public CaptchaController(CaptchaService captchaService) {
this.captchaService = captchaService;
}
/**
* description 获取图片验证码
* param []
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/11 13:59
**/
@PostMapping("/get")
public EResponse getDefaultCaptcha() {
JSONObject data;
try {
data = captchaService.createCaptcha();
} catch (IOException e) {
log.error("创建图片验证码时发生错误");
log.error(e.getMessage(), e);
return EResponse.error();
}
return EResponse.ok(data);
}
/**
* description 校验图片验证码
* param [captchaForm]
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/11 15:37
**/
@PostMapping("/verify")
public EResponse verifyCaptcha(@RequestBody @Validated CaptchaForm captchaForm) {
JSONObject data = new JSONObject();
data.put("result", captchaService.verifyCaptcha(captchaForm.getId(), captchaForm.getCaptcha()));
return EResponse.ok(data);
}
}
package com.esv.datacenter.base.module.captcha.form;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
/**
* @description: 图片验证码Form
* @project: base-service
* @name: com.esv.htwl.base.module.captcha.form.CaptchaForm
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 15:19
* @version:1.0
*/
@Data
public class CaptchaForm {
@Length(max = 64, message = "参数id长度不合法")
@NotBlank(message = "参数id不能为空")
private String id;
@Length(max = 10, message = "参数captcha长度不合法")
@NotBlank(message = "参数captcha不能为空")
private String captcha;
}
package com.esv.datacenter.base.module.captcha.service;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
/**
* @description:
* @project: base-service
* @name: com.esv.htwl.base.module.captcha.service.CaptchaService
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 13:59
* @version:1.0
*/
public interface CaptchaService {
/**
* description 创建图片验证码
* param []
* return com.alibaba.fastjson.JSONObject
* author Administrator
* createTime 2020/04/11 14:16
**/
JSONObject createCaptcha() throws IOException;
/**
* description 校验图片验证码
* param [captchaID, captchaCode]
* return java.lang.Boolean
* author Administrator
* createTime 2020/04/11 15:11
**/
Boolean verifyCaptcha(String captchaID, String captchaCode);
}
package com.esv.datacenter.base.module.captcha.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.base.common.util.AESSecretUtils;
import com.esv.datacenter.base.common.util.CaptchaUtils;
import com.esv.datacenter.base.module.captcha.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @description:
* @project: base-service
* @name: com.esv.htwl.base.module.captcha.service.impl.CaptchaServiceImpl
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 14:16
* @version:1.0
*/
@Service("CaptchaService")
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {
@Value("${aes.sha1prng.key:3.1415926535}")
private String AES_KEY;
@Override
public JSONObject createCaptcha() throws IOException {
// 获取图片验证码接口
Object[] objs = CaptchaUtils.createCaptchaImage();
String captchaCode = (String) objs[0];
BufferedImage captchaImage = (BufferedImage) objs[1];
// 创建图片验证码ID
String captchaID = AESSecretUtils.encryptToStr("esv," + captchaCode + "," + System.currentTimeMillis(), AES_KEY);
// base64编码图片
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(captchaImage, "jpg", byteArrayOutputStream);
byteArrayOutputStream.flush();
String base64Img = this.replaceEnter(Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()));
// 返回数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", captchaID);
jsonObject.put("captcha", "data:image/png;base64," + base64Img);
return jsonObject;
}
@Override
public Boolean verifyCaptcha(String captchaID, String captchaCode) {
String captchaInfo;
try {
captchaInfo = AESSecretUtils.decryptToStr(captchaID, AES_KEY);
} catch (Exception e) {
log.error("AES解析图片ID信息失败");
return false;
}
String[] captchaInfos = captchaInfo.split(",");
if (3 != captchaInfos.length) {
return false;
}
if (!"esv".equals(captchaInfos[0])) {
return false;
}
String code4ID = captchaInfo.split(",")[1];
if (captchaCode.equalsIgnoreCase(code4ID)) {
return true;
} else {
return false;
}
}
private String replaceEnter(String str) {
String reg = "[\n-\r]";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
return m.replaceAll("");
}
}
package com.esv.datacenter.base.module.city.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.base.common.response.EResponse;
import com.esv.datacenter.base.module.city.service.BaseCityCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @description: 地理信息服务,城市服务
* @project: base-service
* @name: com.esv.htwl.base.module.city.controller.BaseCityController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/10 15:18
* @version:1.0
*/
@Slf4j
@RestController
@RequestMapping("/geo/city")
public class BaseCityController {
private BaseCityCodeService baseCityCodeService;
@Autowired
public BaseCityController(BaseCityCodeService baseCityCodeService) {
this.baseCityCodeService = baseCityCodeService;
}
/**
* description 获取全国省市行政区划(树形结构)
* param []
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/10 15:22
**/
@PostMapping("/getAllRegion")
public EResponse getAllRegion() {
List<JSONObject> data = baseCityCodeService.getAllRegionTree();
return EResponse.ok(data);
}
/**
* description 获取全国城市列表数据(键值对)
* param []
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/05/08 15:33
**/
@PostMapping("/getAllRegionMap")
public EResponse getAllRegionMap() {
return EResponse.ok(baseCityCodeService.getAllRegionMap());
}
}
package com.esv.datacenter.base.module.city.dao;
import com.esv.datacenter.base.module.city.entity.BaseCityCodeEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 全国行政区划表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-10 09:30:08
*/
@Mapper
public interface BaseCityCodeDao extends BaseMapper<BaseCityCodeEntity> {
}
package com.esv.datacenter.base.module.city.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 全国行政区划表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-10 10:19:46
*/
@Data
@TableName("base_city_code")
public class BaseCityCodeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
* 行政区划代码
*/
private String code;
/**
* 行政区划全称
*/
private String fullName;
/**
* 行政区划简称
*/
private String briefName;
/**
* 行政区划简称拼音
*/
private String briefNameSpell;
/**
* 上级行政区划代码
*/
private String parentCode;
/**
* 行政级别:1-省、2-市、3-区县
*/
private String level;
/**
* 政府所在地经度
*/
private BigDecimal governmentLon;
/**
* 政府所在地纬度
*/
private BigDecimal governmentLat;
/**
* 行政区域中心点经度
*/
private BigDecimal regionLon;
/**
* 行政区域中心点纬度
*/
private BigDecimal regionLat;
/**
* 是否删除:0-未删除、1-已删除
*/
@TableLogic
private Boolean deleted;
/**
* 创建者
*/
private String createUser;
/**
* 修改者
*/
private String updateUser;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
}
package com.esv.datacenter.base.module.city.service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.datacenter.base.module.city.entity.BaseCityCodeEntity;
import java.util.List;
import java.util.Map;
/**
* 全国行政区划表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-10 09:30:08
*/
public interface BaseCityCodeService extends IService<BaseCityCodeEntity> {
/**
* description 获取全国城市列表数据(树形结构)
* param []
* return java.util.List<com.alibaba.fastjson.JSONObject>
* author Administrator
* createTime 2020/04/10 15:17
**/
List<JSONObject> getAllRegionTree();
/**
* description 获取全国城市列表数据(键值对)
* param []
* return com.alibaba.fastjson.JSONObject
* author Administrator
* createTime 2020/05/08 15:28
**/
Map<String, String> getAllRegionMap();
}
package com.esv.datacenter.base.module.city.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.datacenter.base.common.em.DbDeletedEnum;
import com.esv.datacenter.base.module.city.dao.BaseCityCodeDao;
import com.esv.datacenter.base.module.city.entity.BaseCityCodeEntity;
import com.esv.datacenter.base.module.city.service.BaseCityCodeService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("baseCityCodeService")
public class BaseCityCodeServiceImpl extends ServiceImpl<BaseCityCodeDao, BaseCityCodeEntity> implements BaseCityCodeService {
@Override
@Cacheable(value = "htwl-base-service::geo::city", key="'allTree'")
public List<JSONObject> getAllRegionTree() {
// 查询全国行政区划列表
List<BaseCityCodeEntity> cityCodeEntityList = this.baseMapper.selectList(new LambdaQueryWrapper<BaseCityCodeEntity>()
.select(BaseCityCodeEntity::getCode, BaseCityCodeEntity::getBriefName, BaseCityCodeEntity::getParentCode, BaseCityCodeEntity::getLevel)
.eq(BaseCityCodeEntity::getDeleted, DbDeletedEnum.NO.getCode())
.orderByAsc(BaseCityCodeEntity::getCode));
// 构造返回数据
List<JSONObject> provinceList = new ArrayList<>();
List<JSONObject> cityList = null;
List<JSONObject> districtList = null;
JSONObject province = null;
JSONObject city = null;
JSONObject district;
BaseCityCodeEntity entity;
String cityCode = null;
int citySize = cityCodeEntityList.size();
for (int i = 0; i < citySize; i++) {
entity = cityCodeEntityList.get(i);
if ("1".equals(entity.getLevel())) {
if (null != province) {
city.put("districtList", districtList);
cityList.add(city);
province.put("cityList", cityList);
provinceList.add(province);
city = null;
}
province = new JSONObject();
province.put("code", entity.getCode());
province.put("name", entity.getBriefName());
cityList = new ArrayList<>();
} else if ("2".equals(entity.getLevel())) {
if (null != city) {
city.put("districtList", districtList);
cityList.add(city);
}
city = new JSONObject();
cityCode = entity.getCode();
city.put("code", entity.getCode());
city.put("name", entity.getBriefName());
districtList = new ArrayList<>();
} else {
if (!cityCode.equals(entity.getParentCode())) {
city.put("districtList", districtList);
districtList = new ArrayList<>();
}
district = new JSONObject();
district.put("code", entity.getCode());
district.put("name", entity.getBriefName());
districtList.add(district);
}
if (citySize == (i + 1)) {
city.put("districtList", districtList);
cityList.add(city);
province.put("cityList", cityList);
provinceList.add(province);
}
}
return provinceList;
}
@Override
@Cacheable(value = "htwl-base-service::geo::city", key="'allMap'")
public Map<String, String> getAllRegionMap() {
// 查询全国行政区划列表
List<BaseCityCodeEntity> cityCodeEntityList = this.baseMapper.selectList(new LambdaQueryWrapper<BaseCityCodeEntity>()
.select(BaseCityCodeEntity::getCode, BaseCityCodeEntity::getBriefName, BaseCityCodeEntity::getParentCode, BaseCityCodeEntity::getLevel)
.eq(BaseCityCodeEntity::getDeleted, DbDeletedEnum.NO.getCode())
.orderByAsc(BaseCityCodeEntity::getCode));
// 遍历
Map<String, String> data = new HashMap<>(cityCodeEntityList.size());
cityCodeEntityList.forEach(baseCityCodeEntity -> {
data.put(baseCityCodeEntity.getCode(), baseCityCodeEntity.getBriefName());
});
return data;
}
}
\ No newline at end of file
package com.esv.datacenter.base.module.dict.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.datacenter.base.common.response.EResponse;
import com.esv.datacenter.base.module.dict.service.DicTypeService;
import com.esv.datacenter.base.module.dict.service.GoodsTypeService;
import com.esv.datacenter.base.common.exception.EException;
import com.esv.datacenter.base.common.validator.groups.ValidatorDetail;
import com.esv.datacenter.base.module.dict.entity.DicEntity;
import com.esv.datacenter.base.module.dict.form.DetailForm;
import com.esv.datacenter.base.module.dict.form.DictForm;
import com.esv.datacenter.base.module.dict.service.DicService;
import com.esv.datacenter.base.module.dict.service.VehicleTypeService;
import com.esv.datacenter.base.module.dict.vo.TreeVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @description: 字典表Controller
* @project: base-service
* @name: com.esv.htwl.base.module.dict.controller.DictionaryController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 9:59
* @version:1.0
*/
@Slf4j
@RestController
@RequestMapping("/dict")
public class DictionaryController {
private DicService dicService;
DicTypeService dicTypeService;
private GoodsTypeService goodsTypeService;
private VehicleTypeService vehicleTypeService;
@Autowired
public DictionaryController(DicService dicService, DicTypeService dicTypeService,
GoodsTypeService goodsTypeService, VehicleTypeService vehicleTypeService) {
this.dicService = dicService;
this.dicTypeService = dicTypeService;
this.goodsTypeService = goodsTypeService;
this.vehicleTypeService = vehicleTypeService;
}
/**
* description 获取字典表
* param [form]
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/11 10:30
**/
@PostMapping("/get")
public EResponse getDictByTypes(@RequestBody DictForm form) {
String[] types;
if (StringUtils.isBlank(form.getType())) {
List<String> validTypeList = dicTypeService.getAllValidType();
types = validTypeList.toArray(new String[validTypeList.size()]);
} else {
types = form.getType().split(",");
}
List<JSONObject> data = dicService.getDictByTypes(types);
return EResponse.ok(data);
}
/**
* description 获取字典名称
* param [form]
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/21 14:32
**/
@PostMapping("/getName")
public EResponse getName(@RequestBody @Validated(ValidatorDetail.class) DictForm form) {
DicEntity entity = dicService.getName(form);
if (null == entity) {
throw new EException(1001, "未找到对应的字典数据");
}
JSONObject data = new JSONObject();
data.put("name", entity.getName());
return EResponse.ok(data);
}
/**
* description 获取货物类型基础数据
* param []
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/20 15:56
**/
@PostMapping("/getGoodsType")
public EResponse getGoodsType() {
List<TreeVO> data = goodsTypeService.getAllGoodsType();
return EResponse.ok(data);
}
/**
* description 获取货物名称
* param [form]
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/22 17:48
**/
@PostMapping("/getGoodsNameByCode")
public EResponse getGoodsNameByCode(@RequestBody @Validated(ValidatorDetail.class) DetailForm form) {
String name = goodsTypeService.getGoodsNameByCode(form.getCode());
JSONObject data = new JSONObject();
data.put("name", name);
return EResponse.ok(data);
}
/**
* description 获取车辆类型基础数据
* param []
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/20 16:38
**/
@PostMapping("/getVehicleType")
public EResponse getVehicleType() {
List<TreeVO> data = vehicleTypeService.getAllVehicleType();
return EResponse.ok(data);
}
/**
* description 获取车辆名称
* param [form]
* return com.esv.freight.base.common.response.EResponse
* author Administrator
* createTime 2020/04/22 17:49
**/
@PostMapping("/getVehicleNameByCode")
public EResponse getVehicleNameByCode(@RequestBody @Validated(ValidatorDetail.class) DetailForm form) {
String name = vehicleTypeService.getVehicleNameByCode(form.getCode());
JSONObject data = new JSONObject();
data.put("name", name);
return EResponse.ok(data);
}
}
package com.esv.datacenter.base.module.dict.dao;
import com.esv.datacenter.base.module.dict.entity.DicEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
*
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-11 09:56:26
*/
@Mapper
public interface DicDao extends BaseMapper<DicEntity> {
/**
* description 获取所有未删除的字典表类型
* param []
* return java.util.List<java.lang.String>
* author Administrator
* createTime 2020/04/11 10:45
**/
List<String> selectAllValidType();
}
package com.esv.datacenter.base.module.dict.dao;
import com.esv.datacenter.base.module.dict.entity.GoodsTypeEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 货物类型基础数据表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-20 15:27:38
*/
@Mapper
public interface GoodsTypeDao extends BaseMapper<GoodsTypeEntity> {
}
package com.esv.datacenter.base.module.dict.dao;
import com.esv.datacenter.base.module.dict.entity.VehicleTypeEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 车辆类型基础数据表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-20 15:27:39
*/
@Mapper
public interface VehicleTypeDao extends BaseMapper<VehicleTypeEntity> {
}
package com.esv.datacenter.base.module.dict.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 业务字典表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-11 09:56:26
*/
@Data
@TableName("base_dic")
public class DicEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
*
*/
private Integer code;
/**
*
*/
private String name;
/**
*
*/
private String type;
/**
*
*/
private Integer orderNum;
/**
*
*/
private String createUser;
/**
*
*/
private String updateUser;
/**
*
*/
private Date createTime;
/**
*
*/
private Date updateTime;
/**
*
*/
@TableLogic
private Boolean deleted;
}
package com.esv.datacenter.base.module.dict.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 货物类型基础数据表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-20 15:27:38
*/
@Data
@TableName("base_goods_type")
public class GoodsTypeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
* 货物类型编码
*/
private Integer code;
/**
* 货物类型名称
*/
private String name;
/**
* 父类型名称
*/
private Integer parentCode;
/**
* 是否删除:0-未删除、1-已删除
*/
@TableLogic
private Boolean deleted;
/**
* 创建者
*/
private String createUser;
/**
* 修改者
*/
private String updateUser;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
}
package com.esv.datacenter.base.module.dict.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 车辆类型基础数据表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-20 15:27:39
*/
@Data
@TableName("base_vehicle_type")
public class VehicleTypeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
*
*/
private Integer code;
/**
* 车型名称
*/
private String name;
/**
*
*/
private Integer parentCode;
/**
* 是否删除:0-未删除、1-已删除
*/
@TableLogic
private Boolean deleted;
/**
* 创建者
*/
private String createUser;
/**
* 修改者
*/
private String updateUser;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
}
package com.esv.datacenter.base.module.dict.form;
import com.esv.datacenter.base.common.validator.groups.ValidatorDetail;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotNull;
/**
* @description: 字典表表单
* @project: base-service
* @name: com.esv.htwl.base.module.dict.form.DetailForm
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 10:08
* @version:1.0
*/
@Data
public class DetailForm {
@NotNull(message = "参数code不能为空", groups = {ValidatorDetail.class})
private Integer code;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.datacenter.base.module.dict.form;
import com.esv.datacenter.base.common.validator.groups.ValidatorDetail;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @description: 字典表表单
* @project: base-service
* @name: com.esv.htwl.base.module.dict.form.DictForm
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 10:08
* @version:1.0
*/
@Data
public class DictForm {
@NotBlank(message = "参数type不能为空", groups = {ValidatorDetail.class})
private String type;
@NotNull(message = "参数code不能为空", groups = {ValidatorDetail.class})
private Integer code;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.datacenter.base.module.dict.service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.datacenter.base.module.dict.form.DictForm;
import com.esv.datacenter.base.module.dict.entity.DicEntity;
import java.util.List;
/**
*
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-11 09:56:26
*/
public interface DicService extends IService<DicEntity> {
/**
* description 获取指定type类型的字典表数据
* param [types]
* return java.util.List<com.alibaba.fastjson.JSONObject>
* author Administrator
* createTime 2020/04/11 10:22
**/
List<JSONObject> getDictByTypes(String[] types);
/**
* description 判断是否有效type类型
* param [type]
* return boolean
* author Administrator
* createTime 2020/04/11 11:04
**/
boolean isValidType(String type);
/**
* description 获取字典名称
* param [form]
* return com.esv.freight.base.module.dict.entity.DicEntity
* author Administrator
* createTime 2020/04/21 14:29
**/
DicEntity getName(DictForm form);
}
package com.esv.datacenter.base.module.dict.service;
import com.esv.datacenter.base.module.dict.entity.DicEntity;
import java.util.List;
/**
* @description:
* @project: base-service
* @name: com.esv.htwl.base.module.dict.service.DicTypeService
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 11:14
* @version:1.0
*/
public interface DicTypeService {
/**
* description 获取指定type类型的字典表数据
* param [type]
* return java.util.List<com.esv.freight.base.module.dict.entity.DicEntity>
* author Administrator
* createTime 2020/04/11 11:27
**/
List<DicEntity> getDictByType(String type);
/**
* description 获取所有未删除的字典表类型
* param []
* return java.util.List<java.lang.String>
* author Administrator
* createTime 2020/04/11 10:41
**/
List<String> getAllValidType();
}
package com.esv.datacenter.base.module.dict.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.datacenter.base.module.dict.entity.GoodsTypeEntity;
import com.esv.datacenter.base.module.dict.vo.TreeVO;
import java.util.List;
/**
* 货物类型基础数据表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-20 15:27:38
*/
public interface GoodsTypeService extends IService<GoodsTypeEntity> {
/**
* description 获取所有获取类型
* param []
* return java.util.List<com.esv.freight.base.module.dict.vo.TreeVO>
* author Administrator
* createTime 2020/04/20 15:42
**/
List<TreeVO> getAllGoodsType();
/**
* description 通过Code获取货物名称
* param [code]
* return java.lang.String
* author Administrator
* createTime 2020/04/22 17:39
**/
String getGoodsNameByCode(Integer code);
}
package com.esv.datacenter.base.module.dict.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.datacenter.base.module.dict.entity.VehicleTypeEntity;
import com.esv.datacenter.base.module.dict.vo.TreeVO;
import java.util.List;
/**
* 车辆类型基础数据表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-20 15:27:39
*/
public interface VehicleTypeService extends IService<VehicleTypeEntity> {
/**
* description 获取所有车辆类型
* param []
* return java.util.List<com.esv.freight.base.module.dict.vo.TreeVO>
* author Administrator
* createTime 2020/04/20 16:35
**/
List<TreeVO> getAllVehicleType();
/**
* description 通过Code获取车辆名称
* param [code]
* return java.lang.String
* author Administrator
* createTime 2020/04/22 17:39
**/
String getVehicleNameByCode(Integer code);
}
package com.esv.datacenter.base.module.dict.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.datacenter.base.module.dict.service.DicTypeService;
import com.esv.datacenter.base.module.dict.dao.DicDao;
import com.esv.datacenter.base.module.dict.entity.DicEntity;
import com.esv.datacenter.base.module.dict.form.DictForm;
import com.esv.datacenter.base.module.dict.service.DicService;
import com.esv.datacenter.base.module.dict.vo.DictVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service("dicService")
public class DicServiceImpl extends ServiceImpl<DicDao, DicEntity> implements DicService {
DicTypeService dicTypeService;
@Autowired
public DicServiceImpl(DicTypeService dicTypeService) {
this.dicTypeService = dicTypeService;
}
@Override
public List<JSONObject> getDictByTypes(String[] types) {
List<JSONObject> dictList = new ArrayList<>();
// 遍历获取数据
String type;
for (int i = 0; i < types.length; i++) {
type = StringUtils.trim(types[i]);
if (StringUtils.isEmpty(type)) {
continue;
}
JSONObject jsonObject = new JSONObject();
List<DictVO> dictVOList = new ArrayList<>();
// 判断是否有效字典表类型
if (this.isValidType(type)) {
List<DicEntity> dicEntityList = dicTypeService.getDictByType(type);
// 数据转换
dicEntityList.forEach(dicEntity -> {
DictVO dictVO = new DictVO();
BeanUtils.copyProperties(dicEntity, dictVO);
dictVOList.add(dictVO);
});
}
jsonObject.put("dictList", dictVOList);
jsonObject.put("type", type);
dictList.add(jsonObject);
}
return dictList;
}
@Override
public boolean isValidType(String type) {
List<String> validTypeList = dicTypeService.getAllValidType();
if (StringUtils.isEmpty(type)) {
return false;
} else {
return validTypeList.contains(type);
}
}
@Override
public DicEntity getName(DictForm form) {
DicEntity queryEntity = new DicEntity();
queryEntity.setType(form.getType());
queryEntity.setCode(form.getCode());
QueryWrapper<DicEntity> queryWrapper = new QueryWrapper<>(queryEntity);
return this.baseMapper.selectOne(queryWrapper);
}
}
\ No newline at end of file
package com.esv.datacenter.base.module.dict.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.esv.datacenter.base.module.dict.dao.DicDao;
import com.esv.datacenter.base.module.dict.entity.DicEntity;
import com.esv.datacenter.base.module.dict.service.DicTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @description:
* @project: base-service
* @name: com.esv.htwl.base.module.dict.service.impl.DicTypeServiceImpl
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 11:15
* @version:1.0
*/
@Service("dicTypeService")
public class DicTypeServiceImpl implements DicTypeService {
private DicDao dicDao;
@Autowired
public DicTypeServiceImpl(DicDao dicDao) {
this.dicDao = dicDao;
}
@Override
@Cacheable(value = "htwl-base-service::dict::type", key="#type")
public List<DicEntity> getDictByType(String type) {
QueryWrapper<DicEntity> queryWrapper = new QueryWrapper<>();
queryWrapper
.select("code", "name")
.eq("type", type)
.orderByAsc("order_num");
return dicDao.selectList(queryWrapper);
}
@Override
@Cacheable(value = "htwl-base-service::dict::type", key="'allValid'")
public List<String> getAllValidType() {
return dicDao.selectAllValidType();
}
}
package com.esv.datacenter.base.module.dict.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.datacenter.base.module.dict.service.GoodsTypeService;
import com.esv.datacenter.base.common.exception.EException;
import com.esv.datacenter.base.module.dict.dao.GoodsTypeDao;
import com.esv.datacenter.base.module.dict.entity.GoodsTypeEntity;
import com.esv.datacenter.base.module.dict.vo.DictVO;
import com.esv.datacenter.base.module.dict.vo.TreeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("goodsTypeService")
public class GoodsTypeServiceImpl extends ServiceImpl<GoodsTypeDao, GoodsTypeEntity> implements GoodsTypeService {
@Override
@Cacheable(value = "htwl-base-service::goods-type", key="'allValid'")
public List<TreeVO> getAllGoodsType() {
// 查询
QueryWrapper<GoodsTypeEntity> queryWrapper = new QueryWrapper<>();
queryWrapper
.select("code", "name", "parent_code")
.orderByAsc("code");
List<GoodsTypeEntity> typeEntityList = this.baseMapper.selectList(queryWrapper);
// 数据转换
List<TreeVO> dataList = new ArrayList<>();
List<DictVO> children;
TreeVO treeVO;
DictVO dictVO;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < typeEntityList.size(); i++) {
GoodsTypeEntity typeEntity = typeEntityList.get(i);
if (null == typeEntity.getParentCode()) {
treeVO = new TreeVO();
BeanUtils.copyProperties(typeEntity, treeVO);
map.put(treeVO.getCode(), i);
dataList.add(treeVO);
} else {
Integer pCode = typeEntity.getParentCode();
if (map.containsKey(pCode)) {
Integer index = map.get(pCode);
treeVO = dataList.get(index);
children = treeVO.getChildren();
if (null == treeVO.getChildren()) {
children = new ArrayList<>();
}
dictVO = new DictVO();
BeanUtils.copyProperties(typeEntity, dictVO);
children.add(dictVO);
treeVO.setChildren(children);
dataList.set(index, treeVO);
}
}
}
return dataList;
}
@Override
@Cacheable(value = "htwl-base-service::goods-type", key="#code")
public String getGoodsNameByCode(Integer code) {
GoodsTypeEntity entity = new GoodsTypeEntity();
entity.setCode(code);
QueryWrapper<GoodsTypeEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.setEntity(entity);
GoodsTypeEntity goodsTypeEntity = this.getOne(queryWrapper);
if (null == goodsTypeEntity) {
throw new EException(1001, "无效的code");
}
return goodsTypeEntity.getName();
}
}
\ No newline at end of file
package com.esv.datacenter.base.module.dict.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.datacenter.base.common.exception.EException;
import com.esv.datacenter.base.module.dict.dao.VehicleTypeDao;
import com.esv.datacenter.base.module.dict.entity.VehicleTypeEntity;
import com.esv.datacenter.base.module.dict.service.VehicleTypeService;
import com.esv.datacenter.base.module.dict.vo.DictVO;
import com.esv.datacenter.base.module.dict.vo.TreeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("vehicleTypeService")
public class VehicleTypeServiceImpl extends ServiceImpl<VehicleTypeDao, VehicleTypeEntity> implements VehicleTypeService {
@Override
@Cacheable(value = "htwl-base-service::vehicle-type", key="'allValid'")
public List<TreeVO> getAllVehicleType() {
// 查询
QueryWrapper<VehicleTypeEntity> queryWrapper = new QueryWrapper<>();
queryWrapper
.select("code", "name", "parent_code")
.orderByAsc("code");
List<VehicleTypeEntity> typeEntityList = this.baseMapper.selectList(queryWrapper);
// 数据转换
List<TreeVO> dataList = new ArrayList<>();
List<DictVO> children;
TreeVO treeVO;
DictVO dictVO;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < typeEntityList.size(); i++) {
VehicleTypeEntity typeEntity = typeEntityList.get(i);
if (null == typeEntity.getParentCode()) {
treeVO = new TreeVO();
BeanUtils.copyProperties(typeEntity, treeVO);
map.put(treeVO.getCode(), i);
dataList.add(treeVO);
} else {
Integer pCode = typeEntity.getParentCode();
if (map.containsKey(pCode)) {
Integer index = map.get(pCode);
treeVO = dataList.get(index);
children = treeVO.getChildren();
if (null == treeVO.getChildren()) {
children = new ArrayList<>();
}
dictVO = new DictVO();
BeanUtils.copyProperties(typeEntity, dictVO);
children.add(dictVO);
treeVO.setChildren(children);
dataList.set(index, treeVO);
}
}
}
return dataList;
}
@Override
@Cacheable(value = "htwl-base-service::vehicle-type", key="#code")
public String getVehicleNameByCode(Integer code) {
VehicleTypeEntity entity = new VehicleTypeEntity();
entity.setCode(code);
QueryWrapper<VehicleTypeEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.setEntity(entity);
VehicleTypeEntity vehicleTypeEntity = this.getOne(queryWrapper);
if (null == vehicleTypeEntity) {
throw new EException(1001, "无效的code");
}
return vehicleTypeEntity.getName();
}
}
\ No newline at end of file
package com.esv.datacenter.base.module.dict.vo;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* @description: 字典表VO
* @project: base-service
* @name: com.esv.htwl.base.module.dict.vo.DictVO
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/11 10:13
* @version:1.0
*/
@Data
public class DictVO {
private Integer code;
private String name;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.datacenter.base.module.dict.vo;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.List;
/**
* @description:
* @project: freight-base-service
* @name: com.esv.htwl.base.module.dict.vo.TreeVO
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/20 15:40
* @version:1.0
*/
@Data
public class TreeVO {
private Integer code;
private String name;
private List<DictVO> children;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.datacenter.base.module.test.controller;
import com.esv.datacenter.base.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.base.*.*.entity,com.esv.datacenter.base.*.*.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
#AES对称加密秘钥
aes:
sha1prng:
key: datacenter-base-servie-3.1415926535
\ 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.base.*.*.entity,com.esv.datacenter.base.*.*.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
#AES对称加密秘钥
aes:
sha1prng:
key: datacenter-base-servie-3.1415926535
\ 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.base.*.*.entity,com.esv.datacenter.base.*.*.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
#AES对称加密秘钥
aes:
sha1prng:
key: datacenter-base-servie-3.1415926535
\ 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.base.*.*.entity,com.esv.datacenter.base.*.*.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
#AES对称加密秘钥
aes:
sha1prng:
key: datacenter-base-servie-3.1415926535
\ No newline at end of file
server:
port: 8031
servlet:
context-path: /base
nacos:
url: 192.168.31.248:8848
namespace: 1697ea67-be4c-4d38-b00d-39392b9dee8f
group: DEFAULT_GROUP
spring:
application:
name: datacenter-base-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
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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