threadLocal的运用

复制代码
 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //使用哪一个取决于springmvc在保存request信息时具体用的子类,他们通常无父子单独实现、
        //如果有父子可以继承第一个持有的httpServletRequest
        HttpServletRequest request = ((ServletWebRequest) requestAttributes).getRequest();
        //ServletRequestAttributes它是spring的具体保存的实例实现,通过名字和实现目的 接口是属性目的获取请求servlet
//        ServletRequestAttributes它是最上乘的类其他实现者以继承它保存的request并初始出自己的,并提供自己的get和set
         HttpServletRequest request1 = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletRequest request3 = ((StandardServletAsyncWebRequest) requestAttributes).getRequest();

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        System.out.println(requestURI+method);

抽象类 RequestContextHolder提供静态方法,获取全局的threadlocal对象,对象中存一个请求属性对象接口,该接口有多个实现类,提供顶层接口以外的附加功能,但在springMVC中把请求保存在当前线程的只会有一个实例实现,其他实例通过继承这个实例同样持有到属性接口实例持有的HttpServletRequest对象,通过 RequestContextHolder类为每一个请求到的线程中都加上一个缓存map,值的接口实例持有请求属性,由于是静态的属性所以所有线程可以使用设置自己的值,获取线程之间存值有交集

复制代码
 private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
    private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
相关推荐
盗理者4 小时前
AI Agent 技能分享|SQL 性能诊断与优化
java·sql·spring·skill
月光有害9 小时前
理解 Spring 依赖注入:从构造器注入到集合与条件 Bean
java·后端·spring
小当家.1059 小时前
LLM服务缓存与连接池管理:三层缓存架构与ChatClient池化
java·后端·spring·缓存·llm·agent
小当家.1059 小时前
Token成本控制实战:语义缓存、上下文压缩与工具缓存
java·spring·缓存·token·上下文
IT利刃出鞘10 小时前
SpringBoot--解决@Valid放在接口的List上时无效的问题
java·spring
IKUN家族20 小时前
Spring IoC&DI
java·spring·rpc
山荷枝1 天前
03-框架--Spring
java·后端·spring
952361 天前
Spring-cloud配置中心
java·spring·spring cloud·微服务
真上帝的左手1 天前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录
java·spring·架构·sso
952361 天前
Sentinel
java·后端·spring·sentinel·springcloud