Commit e973d377 authored by huangcb's avatar huangcb

Init

parents
*.class
*.iml
*.log
/*.iml
/.idea/
/log/
/logs/
*/target/
/target/
FROM 192.168.31.249:5000/java8:0.0.1
RUN mkdir /jar
WORKDIR /jar
#ARG JAR_FILE
ADD target/freight-customer-service.jar /jar/app.jar
ENTRYPOINT ["java", "-jar", "/jar/app.jar"]
\ 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.freight</groupId>
<artifactId>freight-customer-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>freight-customer-service</name>
<description>freight-customer-service</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<docker.image.prefix>springio</docker.image.prefix>
<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.21</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>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>
<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>false</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>freight-customer-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>
<!-- docker打包插件 -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<repository>${docker.image.prefix}/${project.artifactId}</repository>
<buildArgs>
<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
package com.esv.freight.notice;
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: 启动类
* @project: freight-file-service
* @name: com.esv.freight.customer.CustomerApplication
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/07 15:17
* @version:1.0
*/
@SpringBootApplication
@EnableDiscoveryClient
public class CustomerApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerApplication.class, args);
}
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
@PostConstruct
void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
}
}
package com.esv.freight.notice.common.em;
/**
* @description: DB记录是否删除标识
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.common.exception;
/**
* @description: 自定义业务异常
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.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.freight.customer.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("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.freight.notice.common.filter;
import com.esv.freight.notice.common.wrapper.RestRequestWrapper;
import com.esv.freight.notice.common.wrapper.RestResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.freight.customer.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 doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
RestRequestWrapper requestWrapper = new RestRequestWrapper((HttpServletRequest)servletRequest);
RestResponseWrapper responseWrapper = new RestResponseWrapper((HttpServletResponse) servletResponse);
String reqContentType = StringUtils.trimToEmpty(requestWrapper.getContentType()).toLowerCase();
if (reqContentType.contains("multipart/form-data")) {
log.info("multipart/form-data request");
} else {
// 日志输出请求
logReq(requestWrapper);
}
filterChain.doFilter(requestWrapper, responseWrapper);
String resContentType = StringUtils.trimToEmpty(responseWrapper.getContentType());
if (resContentType.contains("text") || resContentType.contains("xml")
|| resContentType.contains("json")) {
// 日志输出返回
try {
logRes(requestWrapper, responseWrapper);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
log.info("Response ContentType: {}", resContentType);
}
}
@Override
public void destroy() {
}
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("UTF-8")));
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();
if ("GET".equalsIgnoreCase(method)) {
Enumeration em = requestWrapper.getParameterNames();
String reqParams = "";
while (em.hasMoreElements()) {
String k = em.nextElement().toString();
String v = requestWrapper.getParameter(k);
reqParams += "&" + k + "=" + v;
}
reqParams = reqParams.replaceFirst("&", "");
if (url.startsWith("/actuator")) {
log.debug("[IP={}]收到{}请求,url:{},params:{}", getHttpClientIp(requestWrapper), method, url, reqParams);
} else {
log.info("[IP={}]收到{}请求,url:{},params:{}", getHttpClientIp(requestWrapper), method, url, reqParams);
}
} else if ("POST".equalsIgnoreCase(method)) {
log.info("[IP={}]收到{}请求,url:{},body:{}", getHttpClientIp(requestWrapper), method, url, getPostBodyStr(requestWrapper));
} else {
}
}
private void logRes(RestRequestWrapper requestWrapper, RestResponseWrapper responseWrapper) throws Exception {
byte[] bytes = responseWrapper.getBody();
String resStr = new String(bytes,"utf-8");
String url = requestWrapper.getRequestURI();
if (url.startsWith("/actuator")) {
log.debug("请求响应:{}", resStr);
} else {
log.info("请求响应:{}", resStr);
}
}
private String getHttpClientIp(HttpServletRequest req){
String ip = req.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getRemoteAddr();
}
return ip;
}
}
\ No newline at end of file
package com.esv.freight.notice.common.handler;
import com.esv.freight.notice.common.exception.EException;
import com.esv.freight.notice.common.response.ECode;
import com.esv.freight.notice.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.freight.customer.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.freight.notice.common.response;
/**
* @description: 系统响应码
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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 THIRD_PARTY_ERROR = new ECode(605, "请求第三方服务失败");
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.freight.notice.common.response;
import java.io.Serializable;
/**
* @description: Rest请求统一返回对象
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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;
}
}
\ No newline at end of file
package com.esv.freight.notice.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.freight.customer.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.freight.notice.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.freight.customer.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.freight.notice.common.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @description:Http请求工具类
* @author:hcbmailbox@163.com
* @date:2019/12/25
*/
@Slf4j
public class ReqUtils {
public static String getRequestHeader(String headerKey) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
return request.getHeader(headerKey);
}
/**
* 获得Http客户端的ip
* @param req
* @return
*/
public static String getHttpClientIp(HttpServletRequest req){
String ip = req.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getRemoteAddr();
}
return ip;
}
}
package com.esv.freight.notice.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:删除记录
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 数校验分组:记录详情
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:新增记录
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:查询列表
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.common.validator.groups;
import javax.validation.groups.Default;
/**
* @description: 参数校验分组:更新记录
* @project: SpringCloudTemplate
* @name: com.esv.freight.customer.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.freight.notice.common.vo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import java.util.List;
/**
* @description: 分页查询返回结果VO
* @project: freight-file-service
* @name: com.esv.freight.customer.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<?> records;
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.records = record;
}
}
package com.esv.freight.notice.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.freight.customer.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.freight.notice.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.freight.customer.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.freight.notice.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: freight-file-service
* @name: com.esv.freight.customer.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.freight.notice.config;
import com.esv.freight.notice.common.filter.LogbackFilter;
import com.esv.freight.notice.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.freight.customer.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;
}
}
package com.esv.freight.notice.module.test.controller;
import com.esv.freight.notice.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-file-service
* @name: com.esv.freight.customer.module.test.controller.TestController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/07 15:30
* @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/freight?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: freight
password: freight
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
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*Dao.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.esv.freight.customer.*.*.entity,com.esv.freight.customer.*.*.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
\ 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/freight?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: freight
password: freight
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
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*Dao.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.esv.freight.customer.*.*.entity,com.esv.freight.customer.*.*.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
server:
port: 1002
servlet:
context-path: /customer
nacos:
url: localhost:8848
namespace: 548b506d-8d19-4d54-9715-bb0ac3a655b2
group: FREIGHT_GROUP
spring:
application:
name: freight-customer-service
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: ${nacos.url}
namespace: ${nacos.namespace}
group: ${nacos.group}
config:
server-addr: ${nacos.url}
namespace: ${nacos.namespace}
group: ${nacos.group}
file-extension: yml
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<springProperty scope="context" name="LOG_FILE_NAME" source="spring.application.name"/>
<!-- 日志存储目录 -->
<property name="LOG_FILE_PATH" value="./logs/" />
<!-- 日志文件大小 -->
<property name="MAX_FILE_SIZE" value="100MB" />
<!-- 日志最大的历史(单位:天) -->
<property name="MAX_HISTORY" value="90" />
<!-- 格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n:换行符-->
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread-%X{traceId}] %-5level %logger{50}.%M[%line]:%msg%n" />
<!-- 控制台输出 -->
<appender name="CONSOLE_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>${LOG_PATTERN}</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
<appender name="FILE_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE_PATH}${LOG_FILE_NAME}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}${LOG_FILE_NAME}-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- mybatis sql日志 日志的级别需要是DEBUG -->
<!-- 日志打印的包的范围,及分类日志文件存储 -->
<logger name="com.esv" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE_APPENDER" />
<appender-ref ref="FILE_APPENDER" />
</logger>
<!--控制台和日志文件输出级别-->
<root level="INFO" additivity="false">
<appender-ref ref="CONSOLE_APPENDER" />
<appender-ref ref="FILE_APPENDER" />
</root>
</configuration>
\ No newline at end of file
package com.esv.freight.notice;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @description:
* @project: freight-file-service
* @name: com.esv.freight.customer.BaseController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 14:09
* @version:1.0
*/
@Slf4j
@Data
public class BaseTestController {
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void before() {
log.info("=================================== Test Start ===================================");
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void after() {
log.info("=================================== Test End ===================================");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment