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");
相关推荐
java资料站2 小时前
十五、Spring AI Alibaba · 高级 ·Graph
java·人工智能·spring
霸道流氓气质3 小时前
基于 Spring @Profile 的 MQ 消费者按需开关设计
java·后端·spring
霸道流氓气质4 小时前
AI 聊天机器人组件:ChatMemory 对话记忆、SSE 心跳保活与可嵌入组件封装的 Vue3 + Spring AI 生产级实战
人工智能·spring·机器人
萧瑟余晖21 小时前
Spring Security会话管理与CSRF详解
spring·csrf
Wx-bishekaifayuan21 小时前
springboot铜仁非遗之家76938-计算机课程设计、毕业设计
java·spring boot·后端·spring·django·课程设计·旅游
青春不朽5121 天前
Python 里 a is b 有时 True 有时 False?小整数缓存和常量折叠的底层真相
python·spring·缓存
苏渡苇1 天前
Spring Insight:跨服务调用链路是怎么串起来的?
spring boot·后端·spring·系统监控·apm
夕除1 天前
redis--主从还是集群,内存
java·spring·mybatis
霸道流氓气质1 天前
AI 简历制作平台:结构化输出解析、多模板渲染与 PDF 导出的 Vue3 + Spring AI 全栈实战
人工智能·spring·pdf