欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > Spring Boot 项目中如何使用异步任务(案例)

Spring Boot 项目中如何使用异步任务(案例)

2025/2/7 7:16:40 来源:https://blog.csdn.net/qq_58341172/article/details/142761999  浏览:    关键词:Spring Boot 项目中如何使用异步任务(案例)

前置知识:

Spring Boot 项目中如何使用异步任务-CSDN博客

通过AOP和Async,将日志信息异步的记录到数据库中

步骤:

  1. 添加依赖

    <!--aop-->
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
  2. 创建日志切面

/**** 操作日志切面*/
@Component
@Aspect
public class OperLogAspect {@Resourceprivate OperLogService operLogService;@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)" +"||@annotation(org.springframework.web.bind.annotation.PutMapping)" +"||@annotation(org.springframework.web.bind.annotation.DeleteMapping)")public void pc() {}@Around("pc()")public Object around(ProceedingJoinPoint joinPoint) {HttpServletRequest request = ServletUtil.getRequest();int businessType = 0;switch (request.getMethod()) {case "POST":businessType = 1;break;case "PUT":businessType = 2;break;case "DELETE":businessType = 3;break;}OperLog operLog = new OperLog();operLog.setTitle(request.getRequestURI().split("/")[4]);operLog.setBusinessType(businessType);operLog.setMethod(joinPoint.getSignature().getName());operLog.setRequestMethod(request.getMethod());operLog.setOperatorType(1);operLog.setOperName("admin"); // 通过token获取用户名operLog.setRoleName("管理员"); // 通过token获取用户id,然后获取用户的角色operLog.setOperUrl(request.getRequestURL().toString());operLog.setOperIp(AddressUtil.getIpAddr(request));operLog.setOperLocation(AddressUtil.getLocationByIp(operLog.getOperIp()));operLog.setOperParam(Arrays.toString(joinPoint.getArgs()));operLog.setOperTime(LocalDateTime.now());Long start = System.currentTimeMillis();try {// 核心业务Object res = joinPoint.proceed();operLog.setJsonResult(JSONUtil.toJsonStr(res));operLog.setStatus(0);return res;} catch (Throwable e) {operLog.setJsonResult(JSONUtil.toJsonStr(AjaxResult.error(e.getMessage())));operLog.setStatus(1);operLog.setErrorMsg(e.getMessage());throw new RuntimeException(e.getMessage());}finally {Long end = System.currentTimeMillis();operLog.setCostTime(end-start);// 记录操作日志operLogService.add(operLog);}}}

        3.创建日志服务相关接口(entity、mapper、service)

@Service
@Transactional(rollbackFor = Exception.class)
public class OperLogServiceImpl implements OperLogService {@Resourceprivate OperLogMapper operLogMapper;/*** 异步记录操作日志*/@Async@Overridepublic void add(OperLog operLog) {operLogMapper.insert(operLog);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com