代码优化

This commit is contained in:
thinkgem
2025-10-21 12:46:49 +08:00
parent 7369be99cb
commit 9ae8f34160

View File

@@ -23,12 +23,10 @@ import org.springframework.web.servlet.ModelAndView;
*/
public class LogInterceptor extends BaseService implements HandlerInterceptor {
private static final ThreadLocal<Long> startTimeThreadLocal =
new NamedThreadLocal<Long>("LogInterceptor StartTime");
private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("LogInterceptorStartTime");
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
long beginTime = System.currentTimeMillis();// 1、开始时间
startTimeThreadLocal.set(beginTime); // 线程绑定变量(该数据只有当前请求的线程可见)
if (logger.isDebugEnabled()){
@@ -38,25 +36,22 @@ public class LogInterceptor extends BaseService implements HandlerInterceptor {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
if (modelAndView != null && logger.isDebugEnabled()){
logger.debug("ViewName: " + modelAndView.getViewName() + " <<< " + request.getRequestURI() + " >>> " + handler);
logger.debug("ViewName: {} <<< {} >>> {}", modelAndView.getViewName(), request.getRequestURI(), handler);
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
Object handler, Exception ex) {
long endTime = System.currentTimeMillis(); // 2、结束时间
long startTime = 0; // 得到线程绑定的局部变量(开始时间)
if (startTimeThreadLocal != null){
Long time = startTimeThreadLocal.get();
if (time != null){
startTime = time;
}
startTimeThreadLocal.remove(); // 用完之后销毁线程变量数据
Long time = startTimeThreadLocal.get();
if (time != null){
startTime = time;
}
startTimeThreadLocal.remove(); // 用完之后销毁线程变量数据
if (startTime == 0){
startTime = endTime + 1000; // 得到 -1000 方便统计
}