首页 > 其他分享 >Spring 中使用自定义的 ThreadLocal 存储导致的坑

Spring 中使用自定义的 ThreadLocal 存储导致的坑

时间:2022-09-03 14:37:06浏览次数:86  
标签:Exception 自定义 get Spring SecurityContextHolder ThreadLocal static public

  Spring 中有时候我们需要存储一些和 Request 相关联的变量,例如用户的登陆有关信息等,它的生命周期和 Request 相同。一个容易想到的实现办法是使用 ThreadLocal:

  public class SecurityContextHolder {

  private static final ThreadLocal securityContext=new ThreadLocal();

  public static void set(SecurityContext context) {

  securityContext.set(context);

  }

  public static SecurityContext get() {

  return securityContext.get();

  }

  public static void clear() {

  securityContext.remove();

  }

  }

  使用一个自定义的 HandlerInterceptor 将有关信息注入进去:

  @Slf4j

  @Component

  public class RequestInterceptor implements HandlerInterceptor {

  @Override

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws

  Exception {

  try {

  SecurityContextHolder.set(retrieveRequestContext(request));

  } catch (Exception ex) {

  log.warn("读取请求信息失败", ex);

  }

  return true;

  }

  @Override

  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable

  ModelAndView modelAndView) throws Exception {

  SecurityContextHolder.clear();

  }

  通过这样,我们就可以在 Controller 中直接使用这个 context,很方便的获取到有关用户的信息:

  @Slf4j

  @RestController

  class Controller {

  public Result get() {

  long userId=SecurityContextHolder.get().getUserId();

  // ...

  }

  }

  这个方法也是很多博客中使用的。然而这个方法却存在着一个很隐蔽的坑: HandlerInterceptor 的 postHandle 并不总是会调用。

  当 Controller 中出现 Exception:

  @Slf4j

  @RestController

  class Controller {

  public Result get() {

  long userId=SecurityContextHolder.get().getUserId();

  // ...

  throw new RuntimeException();

  }

  }

  或者在 HandlerInterceptor 的 preHandle 中出现 Exception:

  @Slf4j

  @Component

  public class RequestInterceptor implements HandlerInterceptor {

  @Override

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws

  Exception {

  try {

  SecurityContextHolder.set(retrieveRequestContext(request));

  } catch (Exception ex) {

  log.warn("读取请求信息失败", ex);

  }

  // ...

  throw new RuntimeException();

  //...

  return true;

  }

  }

  这些情况下, postHandle 并不会调用。这就导致了 ThreadLocal 变量不能被清理。

  在平常的 Java 环境中,ThreadLocal 变量随着 Thread 本身的销毁,是可以被销毁掉的。但 Spring 由于采用了线程池的设计,响应请求的线程可能会一直常驻,这就导致了变量一直不能被 GC 回收。更糟糕的是,这个没有被正确回收的变量,由于线程池对线程的复用,可能会串到别的 Request 当中,进而直接导致代码逻辑的错误。

  为了解决这个问题,我们可以使用 Spring 自带的 RequestContextHolder ,它背后的原理也是 ThreadLocal,不过它总会被更底层的 Servlet 的 Filter 清理掉,因此不存在泄露的问题。

  下面是一个使用 RequestContextHolder 重写的例子:

  public class SecurityContextHolder {

  private static final String SECURITY_CONTEXT_ATTRIBUTES="SECURITY_CONTEXT";

  public static void setContext(SecurityContext context) {

  RequestContextHolder.currentRequestAttributes().setAttribute(

  SECURITY_CONTEXT_ATTRIBUTES,

  context,

  RequestAttributes.SCOPE_REQUEST);

  }

  public static SecurityContext get() {

  return (SecurityContext)RequestContextHolder.currentRequestAttributes()

  .getAttribute(SECURITY_CONTEXT_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST);

  }

  }

  除了使用 RequestContextHolder 还可以使用 Request Scope 的 Bean,或者使用 ThreadLocalTargetSource ,原理上是类似的。

  需要时刻注意 ThreadLocal 相当于线程内部的 static 变量,是一个非常容易产生泄露的点,因此使用 ThreadLocal 应该额外小心。

标签:Exception,自定义,get,Spring,SecurityContextHolder,ThreadLocal,static,public
From: https://www.cnblogs.com/ebuybay/p/16652519.html

相关文章

  • SpringBoot 异步输出 Logback 日志
    一、介绍1.1LogbackLogback是由log4j创始人设计的另一个开源日志组件,它分为下面下个模块:logback-core:其它两个模块的基础模块logback-classic:它是log4......
  • 阿里druid-spring-boot-starter 配置,个人整理以及遇到的问题(防止之后找不到)
    ​简介,什么是DruidDruid是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池、插件框架和SQL解析器组成。该项目主要是为了扩展JDBC的一些限制,可以让程序员实现一些......
  • 自定义控件——视图的构建过程——视图的测量方法
              对于wrap_content形式的宽高,App需要测量它们的实际长度,需要测量的实体主要有3种:  (1)文本尺寸测量文本尺寸分为文本的宽度和高度,需根......
  • SpringMVC 07: WEB-INF下的资源访问 + SpringMVC拦截器
    WBE-INF目录下的资源访问项目配置和Spring博客集(指SpringMVC02)中配置一样出于对网站资源的安全性保护,放在WBE-INF目录下的资源不可以被外部直接访问在WEB-INF/......
  • springboot整合极光推送使用的基本案例
    1.maven依赖<dependency><groupId>cn.jpush.api</groupId><artifactId>jpush-client</artifactId><version>3.3.9</version></dependency>2.工具类/***极......
  • speing和springMVC总结
    1.为什么使用Spring?1)方便解耦,简化开发通过Spring提供的IoC容器,可以将对象之间的依赖关系交由Spring进行控制,避免硬编码造成的过度耦合。2)AOP编程的......
  • 绕不开的Spring的EL表达式
    https://www.baeldung.com/spring-expression-language1.OverviewTheSpringExpressionLanguage(SpEL)isapowerfulexpressionlanguagethatsupportsquerying......
  • SpringTask
    1.定时任务概述在项目中开发定时任务应该一种比较常见的需求,在Java中开发定时任务主要有三种解决方案:一是使用JDK自带的Timer,二是使用第3三方组件Quartz,三是使用Spri......
  • springboot学习
    springboot学习官方文档:https://spring.io/projects/spring-boot1、简介1.1、什么是spirngboot?springboot在spring的基础之上,搭建起来的框架,能够帮助我们整合市面上......
  • springboot配置类@ConfigurationProperties报错Not registered via @EnableConfigurat
    添加一个@Component可以解决此问题,只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能。......