并发情况下advice记录日志的问题

康贝勒 康贝勒 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
项目中用advice里记录日志,但是请求多的时候数据就错乱了,请问如何解决这个问题?
以下是我的代码:
```java
@Aspect
@Component
@EnableAspectJAutoProxy
public class AdviceApi {
@Autowired
private LogAnalyseService logAnalyseService;

@Bean
public LogChannelCall getBean() {
return new LogChannelCall();
}

private ThreadLocal<Long> startTime = new ThreadLocal<>();

@Pointcut("execution(* com.api.controller.*.*(..))")
public void pointcut() {
}

@Before("pointcut()")
public void before() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
String userId = request.getParameter("userId");
String remoteAddr = request.getRemoteAddr();

logChannelCall.setUserId(userId);
logChannelCall.setIp(remoteAddr);
startTime.set(System.currentTimeMillis());
}

@After("pointcut()")
public void after() {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
boolean successful = response.getStatus() == 200;
logChannelCall.setSuccessful(successful);
}

@AfterReturning("pointcut()")
public void afterReturning() {
logChannelCall.setSuccessful(true);
logChannelCall.setResponseTime(System.currentTimeMillis() - startTime.get());
logAnalyseService.insertV3Log(logChannelCall);
}

@AfterThrowing(throwing = "ex", pointcut = "pointcut() && !pointcutPlayAddress() && !pointcutInnerPlayAddress() && !pointcutProAddress()")
public void afterThrowing(Exception ex) {
logChannelCall.setSuccessful(false);
logChannelCall.setReason(ex.getMessage());
logChannelCall.setResponseTime(System.currentTimeMillis() - startTime.get());
logAnalyseService.insertV3Log(logChannelCall);
}
}
```

在请求量大的时候,A日志的参数会把B日志的参数记录下来,前几天发生这样一件事,A请求正在执行,B请求报了异常,B请求的错误日志被A记录了。请问如何解决?
...全文
评论
收藏 已收藏
分享
返回顶部
康贝勒
Java 51,407 成员 86,172 内容