以下是我的方面:
@Configurable
@Aspect
public class TimingAspect {
@Autowired
private HttpServletRequest httpServletRequest;
// Generic performance logger for any mothod
private Object logPerfomanceInfo(ProceedingJoinPoint joinPoint, String remoteAddress) {
StringBuilder tag = new StringBuilder();
if (joinPoint.getTarget() != null) {
tag.append(joinPoint.getTarget().getClass().getName());
tag.append(".");
}
tag.append(joinPoint.getSignature().getName());
StopWatch stopWatch = new StopWatch(tag.toString());
Object result = joinPoint.proceed(); // continue on the intercepted method
stopWatch.stop();
PerformanceUtils.logInPerf4jFormat(stopWatch.getStartTime(), stopWatch.getElapsedTime(), stopWatch.getTag(), stopWatch.getMessage(), remoteAddress);
return result;
}
@Around("execution(* $$$.$$$.$$$.api.controller.*.*(..))")
public Object logAroundApis(ProceedingJoinPoint joinPoint) throws Throwable {
String remoteAddress = null;
if (httpServletRequest != null) {
remoteAddress = httpServletRequest.getRemoteAddr();
}
return logPerfomanceInfo(joinPoint, remoteAddress);
}
@Around("execution(* $$$.$$$.$$$.$$$.$$$.$$$.*(..))")
public Object logAroundService(ProceedingJoinPoint joinPoint) throws Throwable {
String remoteAddress = null;
if (httpServletRequest != null) {
remoteAddress = httpServletRequest.getRemoteAddr();
}
return logPerfomanceInfo(joinPoint, remoteAddress);
}
我没有收到任何编译时错误,但是当我启动码头服务器时出现以下异常:
嵌套异常是 java.lang.IllegalStateException:未找到线程绑定请求:您指的是实际 Web 请求之外的请求属性,还是在原始接收线程之外处理请求?如果您实际上是在 Web 请求中操作并且仍然收到此消息,则您的代码可能在 DispatcherServlet/DispatcherPortlet 之外运行:在这种情况下,请使用 RequestContextListener 或 RequestContextFilter 来公开当前请求。
这里要注意的一件事是,如果我删除“logAroundService”方法,我不会得到任何异常。
原文由 hrishikeshp19 发布,翻译遵循 CC BY-SA 4.0 许可协议
你不应该在你的方面自动装配
HttpServletRequest
因为这会将你的方面绑定为只能运行从正在执行的HttpServletRequest
中调用的类。而是使用
RequestContextHolder
在需要时获取请求。