以下是我的方面:
@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);
}
我没有收到任何编译时错误,但是当我启动我的 jetty 服务器时出现以下异常:
nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
这里需要注意的一点是,如果我删除“logAroundService”方法,我不会得到任何异常。
最佳答案
您不应该在您的切面中 Autowiring HttpServletRequest
,因为这会将您的切面绑定(bind)为只能对从正在执行的 HttpServletRequest
中调用的类运行。
当您需要时,请改为使用 RequestContextHolder
来获取请求。
private String getRemoteAddress() {
RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
if (attribs instanceof NativeWebRequest) {
HttpServletRequest request = (HttpServletRequest) ((NativeWebRequest) attribs).getNativeRequest();
return request.getRemoteAddr();
}
return null;
}
关于java.lang.IllegalStateException : No thread-bound request found, 方面的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24025924/