只有利害关系和出众的才干,才能帮你出起主意来,才认真细到,眼光透彻。——巴尔扎克
我们在web
开发中经常遇到在一个线程中需要共享变量
这里就可以使用ThreadLocal
去完成
例如我们用户发起请求,我们在过滤器等将用户信息存储在ThreadLocal
中,这样在代码中获取用户信息就相对容易
写法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import cn.hutool.core.lang.Opt;
public class UserUtils { private static final ThreadLocal<UserDetail> USER_THREAD = new ThreadLocal<>();
public static void setUser(UserDetail userDetail) { USER_THREAD.set(userDetail); }
public static void clear() { USER_THREAD.remove(); }
public static Opt<UserDetail> getUser() { return Opt.ofNullable(USER_THREAD.get()).or(() -> { UserDetail userDetail = null; return Opt.of(userDetail); }); } }
|
在拦截器中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package com.ruben.xchat.interceptor;
import com.ruben.xchat.utils.UserUtils; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.AsyncHandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
@Component public class UserInfoInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { UserUtils.getUser().ifPresent(UserUtils::setUser); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserUtils.clear(); } }
|
然后别忘了让拦截器生效
1 2 3 4 5 6 7 8 9 10 11 12
| @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Resource private UserInfoInterceptor userInfoInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(userInfoInterceptor).addPathPatterns("/**"); } }
|