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

康贝勒 2021-04-16 09:46:49
项目中用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记录了。请问如何解决?
...全文
44 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50,526

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧