![SpringBoot项目基础设施搭建](http://img.jiangsulong.com/221118/13364910O-0.jpg)
文章插图
前言
准确点说 , 这不是《从零打造项目》系列的第一篇文章 , 模版代码生成的那个项目讲解算是第一篇 , 当时就打算做一套项目脚手架 , 为后续进行项目练习做准备 。因时间及个人经验问题 , 一直拖到现在才继续实施该计划 , 希望这次能顺利完成 。
每个项目中都会有一些共用的代码 , 我们称之为项目的基础设施 , 随拿随用 。本文主要介绍 SpringBoot 项目中的一些基础设施 , 后续还会详细介绍 SpringBoot 分别结合 MyBatis、MybatisPlus、JPA 这三种 ORM 框架进行项目搭建 , 加深大家对项目的掌握能力 。
因内容篇幅过长 , 本来这些基础设施代码应该分布在未来的三篇文章中 , 被提取出来 , 专门写一篇文章来介绍 。
SpringBoot项目基础代码引入依赖
org.springframework.bootspring-boot-starter-parent2.6.31.81.2.735.5.18.0.192.1.44.1.5struct.version>1.4.2.Final1.18.20org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-aoporg.springframework.bootspring-boot-starter-securityorg.springframework.bootspring-boot-starter-validationcom.alibabafastjson${fastJSON.version}cn.hutoolhutool-all${hutool.version}org.projectlomboklombok${org.projectlombok.version}trueorg.springframework.bootspring-boot-starter-testtestMySQLmysql-connector-JAVA${mysql.version}runtimeorg.springframework.dataspring-data-commons2.4.6org.springdocspringdoc-openapi-ui1.6.9com.alibabadruid-spring-boot-starter1.1.18org.Mapstructmapstruct${org.mapstruct.version}org.mapstructmapstruct-processor${org.mapstruct.version}org.springframework.bootspring-boot-maven-plugin复制代码
有些依赖不一定是最新版本 , 而且你看到这篇文章时 , 可能已经发布了新版本 , 到时候可以先模仿着将项目跑起来后 , 再根据自己的需求来升级各项依赖 , 有问题咱再解决问题 。
日志请求切面
项目进入联调阶段 , 服务层的接口需要和协议层进行交互 , 协议层需要将入参[json字符串]组装成服务层所需的 json 字符串 , 组装的过程中很容易出错 。入参出错导致接口调试失败问题在联调中出现很多次 , 因此就想写一个请求日志切面把入参信息打印一下 , 同时协议层调用服务层接口名称对不上也出现了几次 , 通过请求日志切面就可以知道上层是否有没有发起调用 , 方便前后端甩锅还能拿出证据 。
首先定义一个请求日志类 , 记录一些关键信息 。
@Data@EqualsAndHashCode(callSuper = false)public class requestLog {// 请求ipprivate String ip;// 访问urlprivate String url;// 请求类型private String httpMethod;// 请求方法名(绝对路径)private String classMethod;// 请求方法描述private String methodDesc;// 请求参数private Object requestParams;// 返回结果private Object result;// 操作时间private Long operateTime;// 消耗时间private Long timeCost;// 错误信息private JSONObject errorMessage;复制代码
然后根据 @Aspect 实现日志切面记录
@Component@Aspect@Slf4jpublic class RequestLogAspect {@Pointcut("execution(* com.msdn.orm.hresh.controller..*(..))")public void requestServer() {@Around("requestServer()")public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {long start = System.currentTimeMillis();//获取当前请求对象RequestLog requestLog = getRequestLog();Object result = proceedingJoinPoint.proceed();Signature signature = proceedingJoinPoint.getSignature();// 请求方法名(绝对路径)requestLog.setClassMethod(String.format("%s.%s", signature.getDeclaringTypeName(),signature.getName()));// 请求参数requestLog.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));// 返回结果requestLog.setResult(result);// 如果返回结果不为null , 则从返回结果中剔除返回数据 , 查看条目数、返回状态和返回信息等if (!ObjectUtils.isEmpty(result)) {JSONObject jsonObject = JSONUtil.parseobj(result);Object data = https://www.isolves.com/it/cxkf/kj/2022-11-18/jsonObject.get("data");if (!ObjectUtils.isEmpty(data) && data.toString().length() > 200) {// 减少日志记录量 , 比如大量查询结果 , 没必要记录jsonObject.remove("data");requestLog.setResult(jsonObject);// 获取请求方法的描述注解信息MethodSignature methodSignature = (MethodSignature) signature;Method method = methodSignature.getMethod();if (method.isAnnotationPresent(Operation.class)) {Operation methodAnnotation = method.getAnnotation(Operation.class);requestLog.setMethodDesc(methodAnnotation.description());// 消耗时间requestLog.setTimeCost(System.currentTimeMillis() - start);log.info("Request Info : {}", JSONUtil.toJsonStr(requestLog));return result;@AfterThrowing(pointcut = "requestServer()", throwing = "e")public void doAfterThrow(JoinPoint joinPoint, Runtimeexception e) {try {RequestLog requestLog = getRequestLog();Signature signature = joinPoint.getSignature();// 请求方法名(绝对路径)requestLog.setClassMethod(String.format("%s.%s", signature.getDeclaringTypeName(),signature.getName()));// 请求参数requestLog.setRequestParams(getRequestParamsByJoinPoint(joinPoint));StackTraceElement[] stackTrace = e.getStackTrace();// 将异常信息转换成jsonJSONObject jsonObject = new JSONObject();if (!ObjectUtils.isEmpty(stackTrace)) {StackTraceElement stackTraceElement = stackTrace[0];jsonObject = JSONUtil.parseObj(JSONUtil.toJsonStr(stackTraceElement));// 转换成jsonjsonObject.set("errorContent", e.getMessage());jsonObject.set("createTime", DateUtil.date());jsonObject.setDateFormat(DatePattern.NORM_DATETIME_PATTERN);jsonObject.set("messageId", IdUtil.fastSimpleUUID());// 获取IP地址jsonObject.set("serverIp",.NETUtil.getLocalhostStr());requestLog.setErrorMessage(jsonObject);log.error("Error Request Info : {}", JSONUtil.toJsonStr(requestLog));} catch (Exception exception) {log.error(exception.getMessage());private RequestLog getRequestLog() {//获取当前请求对象ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();// 记录请求信息(通过Logstash传入Elasticsearch)RequestLog requestLog = new RequestLog();if (!ObjectUtils.isEmpty(attributes) && !ObjectUtils.isEmpty(attributes.getRequest())) {HttpServletRequest request = attributes.getRequest();// 请求iprequestLog.setIp(request.getRemoteAddr());// 访问urlrequestLog.setUrl(request.getRequestURL().toString());// 请求类型requestLog.setHttpMethod(request.getMethod());return requestLog;* 根据方法和传入的参数获取请求参数* @param proceedingJoinPoint 入参* @return 返回private Map getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {//参数名String[] paramNames = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();//参数值Object[] paramValues = proceedingJoinPoint.getArgs();return buildRequestParam(paramNames, paramValues);private Map getRequestParamsByJoinPoint(JoinPoint joinPoint) {try {//参数名String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();//参数值Object[] paramValues = joinPoint.getArgs();return buildRequestParam(paramNames, paramValues);} catch (Exception e) {return new HashMap
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 科目二考试有几个项目,科目二考试有时间限制吗
- 李晨|李晨如今在娱乐圈的尴尬咖位,重点项目是客串,近几年没有代表作
- 产检项目及时间表
- 小学运动会开展哪些项目运动好
- 赚钱好项目有哪些?
- 如何寻找互联网创业项目经验 如何寻找互联网创业项目经理
- 如何寻找好的创业项目经验 如何寻找好的创业项目经理
- 招聘|36氪项目报道 | 猎头由专精领域转向全域,Morgan McKinley 中国以项目制人才解决方案寻找新路径
- 汽车保养项目有哪些?
- 卓越|上班族副业推荐,副业赚钱有哪些项目, 可发展的长期副业项目