赞
踩
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.1</version>
</dependency>
官网地址 Druid-Github
完整yml
spring: datasource: druid: url: jdbc:mysql://localhost:3306/aaa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&verifyServerCertificate=false&useSSL=false&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 initial-size: 50 max-active: 400 min-idle: 50 max-wait: 60000 ## Oracle/MySQL 建议关闭 pool-prepared-statements: false max-pool-prepared-statement-per-connection-size: 20 validation-query: SELECT 1 FROM DUAL test-on-borrow: false test-on-return: false test-while-idle: true time-between-eviction-runs-millis: 60000 filter: # 开启druid-datasource的状态监控 stat: enabled: true db-type: mysql # 开启慢sql监控,超过2s 就认为是慢sql,记录到日志中 log-slow-sql: true slow-sql-millis: 2000 web-stat-filter: enabled: true # 启动 StatFilter url-pattern: /* # 过滤所有url exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" # 排除一些不必要的url session-stat-enable: true # 开启session统计功能 session-stat-max-count: 1000 # session的最大个数,默认100 stat-view-servlet: enabled: true # 正常StatViewServlet url-pattern: /druid/* # 访问内置监控页面的路径,内置监控页面的首页是/druid/index.html reset-enable: false # 不允许清空统计数据,重新计算 login-username: admin # 配置监控页面访问密码 login-password: 123456 allow: # 留空表示 允许所有IP访问
http://项目地址/druid/login.html
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * <p> * <h2>Swagger配置</h2> * 中文Swagger手册: https://gumutianqi1.gitbooks.io/specification-doc/content/tools-doc/spring-boot-swagger2-guide.html * </p> * */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) //用于生成API信息 .apiInfo(apiInfo()) //select()函数返回一个ApiSelectorBuilder实例,用来控制接口被swagger做成文档 .select() //用于指定扫描哪个包下的接口,重要 .apis(RequestHandlerSelectors.basePackage("com.mh.aaa")) //选择所有的API,如果你想只为部分API生成文档,可以配置这里 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() //用来自定义API的标题 .title("Spring Build") //用来描述整体的API .description("CSDN博客: https://blog.csdn.net/qq_40739917") //创建人信息 .termsOfServiceUrl("https://blog.csdn.net/qq_40739917") //用于定义服务的域名 .contact("liyangit") //可以用来定义版本 .version("1.0") .build(); }
http://项目路径/swagger-ui.html
加入 swagger-ui.html Handel页面拦截器处理映射
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * <p> * web 配置 * </p> * */ @Configuration public class WebConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 加入 swagger-ui.html 映射,不然会 404找不到页面 registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); // 加入 swagger-ui.html 映射 结束 super.addResourceHandlers(registry); }
在 项目 resource
目录下创建 logback-spring.xml
配置文件,配置文件和 application.yml
同级
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <contextName>logback</contextName> <!-- 日志文件 存储在 项目根路径--> <!-- docker 方式部署日志文件 存储在 项目根路径 --> <property name="log.path" value="logs"/> <!-- 控制台日志 --> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>debug</level> </filter> <encoder> <!--<pattern>%d %p (%file:%line\)- %m%n</pattern>--> <!--格式化输出:%d:表示日期 %thread:表示线程名 %-5level:级别从左显示5个字符宽度 %msg:日志消息 %n:是换行符--> <pattern>%red(日志输出-) %red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger) - %cyan(%msg%n) </pattern> <charset>UTF-8</charset> </encoder> </appender> <!-- info级别日志 --> <appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}/info.txt</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/info-%d{yyyy-MM-dd}.txt</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n </pattern> </encoder> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- error级别日志 --> <appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}/error.txt</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/error-%d{yyyy-MM-dd}.txt</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> </encoder> <!-- 此日志文件只记录ERROR级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!--配置异步日志--> <appender name="console_ASYNC" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="console"/> </appender> <appender name="info_ASYNC" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="info"/> </appender> <appender name="error_ASYNC" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="error"/> </appender> <root level="INFO"> <appender-ref ref="console_ASYNC"/> <appender-ref ref="info_ASYNC"/> <appender-ref ref="error_ASYNC"/> </root> <!-- 针对包路径 级别日志 --> <logger name="org.mybatis" level="ERROR"/> <logger name="org.springframework" level="ERROR"/> <logger name="com.lizr" level="INFO"/> <!-- mapper 需要打印sql,日志级别为 debug --> <!-- <logger name="com.lizr.mapper" level="debug" /> --> </configuration>
在 applicationyml
文件中 引入日志配置文件
## 日志
logging:
config: classpath:logback-spring.xml
查看日志需要详细的运行SQl记录 就要在 logback-spring.xml
增加 debug 日志,但是debug日志产生的文件太大了,只是为了记录SQL得不偿失,这时候就需要 单独把 Mybatis SQL日志改为 Info级别
创建 一个 自定义 日志输出类 StdOutImpl.class
import org.apache.ibatis.logging.Log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 用于 重写 mybatis日志输出, 将原本 mybatis debug级别更改为 info级别 * mybatis日志输出类 请参考: {@link org.apache.ibatis.logging.stdout.StdOutImpl} */ public class StdOutImpl implements Log { private final static Logger log = LoggerFactory.getLogger(StdOutImpl.class); public StdOutImpl(String clazz) { // Do Nothing } @Override public boolean isDebugEnabled() { // 开启 debug日志 return true; } @Override public boolean isTraceEnabled() { return true; } @Override public void error(String s, Throwable e) { log.error(s, e); } @Override public void error(String s) { log.error(s); } @Override public void debug(String s) { // debug日志改为 info输出 log.info(s); } @Override public void trace(String s) { log.trace(s); } @Override public void warn(String s) { log.warn(s); } }
设置 Mybatis日志 并指定 日志类输出
mybatis-plus:
configuration:
log-impl: 自定义日志输出类的路径.StdOutImpl # 使用自定义mybatis日志输出
就可以了
打开 application.yml
关闭 Spring异常自动处理映射
spring:
## 如果没有找到处理请求的处理程序,是否应抛出“NoHandlerFoundException”, 使用自定义处理全局异常处理需要设置为 true
mvc:
throw-exception-if-no-handler-found: true
## 一般下面这个代码不用写,但是 SpringBoot版本 2.6以上 不加下面这一句,捕捉不到 NoHandlerFoundException 404 异常
static-path-pattern: /statics/**
## 关闭默认资源处理,开启的话 如果404、500等错误 会调用SpringBoot默认异常页面处理
resources:
add-mappings: false
文件名 ResponseUtil.java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * 响应操作结果 * * <pre> * { * errno: 错误码, * errmsg:错误消息, * data: 响应数据 * } * </pre> * * <p> * 错误码: * <ul> * <li>4xx,参数错误,即前端没有传递后端需要的参数; * </ul> * <ul> * <li>5xx,服务端异常; * </ul> * <ul> * <li>601未登录 * </ul> */ @SuppressWarnings("all") public class ResponseUtil<T> { private int code; private String msg; private T data; private ResponseUtil(int code, String msg, T data) { this.code = code; this.msg = msg; this.data = data; } /** * 对list数据分页 * * @param list list集合 * @param page 当前页 * @param limit 显示条数 * @return ResponseUtil<?>结果集 */ public static ResponseUtil<?> pageByList(List<?> list, long page, long limit) { HashMap<String, Object> result = new HashMap<>(5); // 总条数 long total = list.size(); // 总页数 long pages = (total / limit) + 1; // 开始下标 Long startIndex = (page - 1) * limit; // 结束下标 Long endIndex = startIndex + limit; if (endIndex > total) { endIndex = total; } List<?> records = new ArrayList<>(); if (total != 0) { records = list.subList(startIndex.intValue(), endIndex.intValue()); } result.put("total", total); result.put("pages", pages); result.put("records", records); result.put("current", page); result.put("size", limit); return ok(result); } public static ResponseUtil<?> ok() { ResponseUtil<?> resp = new ResponseUtil(0, LanguageMessageUtil.getLanguageMessage().getSuccessRequestMessage(), null); return resp; } public static ResponseUtil<?> ok(String msg, Object data) { return new ResponseUtil(0, msg, data); } public static ResponseUtil<?> ok(Object data) { return new ResponseUtil(0, LanguageMessageUtil.getLanguageMessage().getSuccessRequestMessage(), data); } /** * 业务状态 状态码为 401 * * @return */ public static ResponseUtil<?> businessFail(String msg) { return fail(401, msg, null); } /** * 业务状态 状态码为 501 * * @return */ public static ResponseUtil<?> serverFail(String msg) { return fail(501, msg, null); } @Override public String toString() { return "ResponseUtil{" + "状态码:[code] = " + code + ", 响应信息:[msg] = '" + msg + '\'' + ", 响应数据:[data] = " + data + '}'; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
常见的异常
文件名: GlobalExceptionHandler.java
import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.internal.engine.path.PathImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; 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.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.util.Set; import java.util.concurrent.RejectedExecutionException; /** * 全局异常处理 */ @RestControllerAdvice public class GlobalExceptionHandler { private final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); public String getRequestUrl(HttpServletRequest request) { return request.getRequestURL().toString(); } /** * 处理 NoHandlerFoundException 404 异常 * * @return 根据自定义返回结果 返回对应内容 */ @ExceptionHandler(value = NoHandlerFoundException.class) public Object NoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) { String msg = "请求错误,接口路径错误!"; log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", msg, getRequestUrl(request)); log.error("这是具体异常原因: ", e); return ResponseUtil.serverFail(msg); } /** * 处理 POST请求传递JSON,格式不正确 异常 * * @return 根据自定义返回结果 返回对应内容 */ @ExceptionHandler(value = HttpMessageNotReadableException.class) @ResponseBody public Object HttpMessageNotReadableException(HttpMessageNotReadableException e, HttpServletRequest request) { String msg = "解析JSON 格式请求体异常!"; log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", msg, getRequestUrl(request)); log.error("具体原因:", e); return ResponseUtil.serverFail(msg); } /** * 处理 非法参数 异常 * * @return 根据自定义返回结果 返回对应内容 */ @ExceptionHandler(IllegalArgumentException.class) @ResponseBody public ResponseUtil<?> badArgumentHandler(IllegalArgumentException e, HttpServletRequest request) { log.error("非法参数异常, 异常原因: [{}], 接口地址: [{}]", e.getMessage(), getRequestUrl(request)); log.error("这是具体异常原因: ", e); return ResponseUtil.businessFail(e.getMessage()); } /** * 处理 方法参数类型不匹配 异常 * * @return 根据自定义返回结果 返回对应内容 */ @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseBody public Object badArgumentHandler(MethodArgumentTypeMismatchException e, HttpServletRequest request) { log.error("方法参数类型不匹配异常, 异常原因: [{}], 接口地址: [{}]", e.getMessage(), getRequestUrl(request)); log.error("这是具体异常原因: ", e); return ResponseUtil.businessFail(e.getMessage()); } /** * 处理 @NotNull 参数校验失败 异常 * * @return 根据自定义返回结果 返回对应内容 */ @ExceptionHandler(ValidationException.class) @ResponseBody public Object badArgumentHandler(ValidationException e, HttpServletRequest request) { StringBuilder message = new StringBuilder(); if (e instanceof ConstraintViolationException) { ConstraintViolationException exs = (ConstraintViolationException) e; Set<ConstraintViolation<?>> violations = exs.getConstraintViolations(); for (ConstraintViolation<?> item : violations) { message.append(((PathImpl) item.getPropertyPath()).getLeafNode().getName()).append(item.getMessage()); } } String errorMsg = message.toString(); if (StringUtils.isBlank(errorMsg)) { errorMsg = e.getMessage(); } log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", errorMsg, getRequestUrl(request)); return ResponseUtil.serverFail(errorMsg); } /** * 不支持的请求方式异常 * */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody public Object HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) { String error = "不支持: ".concat(e.getMethod()).concat(" 请求方式"); log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", error, getRequestUrl(request)); return ResponseUtil.serverFail(error); } /** * 请求参数异常 * */ @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody public Object missingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) { String error = String.format("参数名称: %s 不能为空,类型: %s", e.getParameterName(), e.getParameterType()); log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", error, getRequestUrl(request)); return ResponseUtil.serverFail(error); } /** * 自定义 处理 MethodArgumentNotValidException 参数校验错误 * * @param e * @return 根据自定义返回结果 返回对应内容 如果 使用的是 org.hibernate.validator jar 的话 使用: * MethodArgumentNotValidException.class 捕捉参数校验异常 如果是 SpringBoot默认的校验 * 使用: org.springframework.validation.BindException.class 捕捉参数校验异常 * 这里使用的是 SpringBoot默认的 */ @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public Object BindException(MethodArgumentNotValidException e, HttpServletRequest request) { // 不拼接全部异常,一个一个输出 /* * for (ObjectError error: e.getBindingResult().getAllErrors()) { * sb.append(error.getDefaultMessage()); sb.append("、"); } String errorMsg = * sb.substring(0,sb.length() - 1).toString(); */ String errorMsg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage(); log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", errorMsg, getRequestUrl(request)); return ResponseUtil.serverFail(errorMsg); } /** * 系统异常 */ @ExceptionHandler(ServiceException.class) @ResponseBody public ResponseUtil<?> ServiceException(ServiceException e, HttpServletRequest request) { log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", e.getMessage(), getRequestUrl(request)); return ResponseUtil.serverFail(e.getMessage()); } /** * 运行时异常异常 */ @ExceptionHandler(RuntimeException.class) @ResponseBody public Object RuntimeException(RuntimeException e, HttpServletRequest request) { log.error("系统异常, 异常原因: [{}], 接口地址: [{}]", e.getMessage(), getRequestUrl(request)); log.error("这是具体异常原因: ", e); return ResponseUtil.serverFail(e.getMessage()); } @ExceptionHandler(RejectedExecutionException.class) @ResponseBody public Object RejectedExecutionException(RejectedExecutionException e, HttpServletRequest request) { log.error("系统异常, 异常原因: [线程池任务已满], 接口地址: [{}]", getRequestUrl(request)); return ResponseUtil.server(LanguageMessageUtil.getLanguageMessage().getTimeOutRequestMessage()); } }
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * * </p> * * @CreateTime */ @RestController public class Controller { @RequestMapping(value = "/") public ResponseUtil<?> hello() { return ResponseUtil.ok("hello word!"); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。