• Spring RequestContextHolder


    RequestContextHolder是Spring提供的一个工具类,用于在多线程环境中存储和访问与当前线程相关的请求上下文信息。它主要用于将当前请求的信息存储在线程范围内,以便在不同的组件中共享和访问这些信息,特别是在没有直接传递参数的情况下。

    1.源码解读

    1. @Nullable
    2. public static RequestAttributes getRequestAttributes() {
    3. RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get();
    4. if (attributes == null) {
    5. attributes = (RequestAttributes)inheritableRequestAttributesHolder.get();
    6. }
    7. return attributes;
    8. }
    9. private static final ThreadLocal requestAttributesHolder = new NamedThreadLocal("Request attributes");
    10. private static final ThreadLocal inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
    11. // requestAttributesHolder.get()
    12. // inheritableRequestAttributesHolder.get()
    13. public T get() {
    14. Thread t = Thread.currentThread();
    15. ThreadLocalMap map = getMap(t);
    16. if (map != null) {
    17. ThreadLocalMap.Entry e = map.getEntry(this);
    18. if (e != null) {
    19. @SuppressWarnings("unchecked")
    20. T result = (T)e.value;
    21. return result;
    22. }
    23. }
    24. return setInitialValue();
    25. }

    从中不难看出RequestContextHolder的底层逻辑是使用ThreadLocal实现的,因此我们不难理解为何RequestContextHolder可以用于在多线程环境中存储和访问与当前线程相关的请求上下文信息。

    ThreadLocal详细介绍

    2.使用 RequestContextHolder

    1. private static HttpServletRequest getHttpServletRequest() {
    2. return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    3. }

    3.其他HttpServletRequest获取方式

    3.1 Controller中加参获取

    1. @PostMapping("/xx")
    2. public String addCustomer(HttpServletRequest request) {
    3. // TODO
    4. request..
    5. return "SUCCESS";
    6. }

    3.2 自动注入

    1. @Controller
    2. public class DemoController{
    3. @Resource
    4. private HttpServletRequest request;
    5. @RequestMapping("/test")
    6. public String test(){
    7. // TODO
    8. request..
    9. return "SUCCESS";
    10. }
    11. }

  • 相关阅读:
    在链表上实现 Partition 以及荷兰国旗问题
    爬虫技术对携程网旅游景点和酒店信息的数据挖掘和分析应用
    python文本操作
    H5新Api | requestIdleCallback - requestAnimationFram
    公网IP和私有IP
    ChatGLM3-6B详细安装过程记录(Linux)
    观察者模式与发布订阅者模式
    L1-011 A-B分数 20
    ORA-01455: converting column overflows integer datatype
    【论文阅读笔记】PA-SAM: Prompt Adapter SAM for High-Quality Image Segmentation
  • 原文地址:https://blog.csdn.net/qq_34253002/article/details/133990523