ThreadLocal - using as context information for REST API with spring-boot

前端 未结 4 1502
温柔的废话
温柔的废话 2021-01-26 09:00

I have some spring-boot application (it exposes rest api). The mentioned REST API is secured by spring-security. Everything is fine, however now I need

相关标签:
4条回答
  • 2021-01-26 09:10
    1. If you use only one thread in your program, the answer is yes. There are no reasons run this operations in different threads, because switching threads is overhead. But in your program you or somebody can define async operations (@Async, Thread.start(), events, etc.) in that case there are more then one thread, and your ThreadLocal will handle value only for the first thread.

    2. Yes, but see first paragraph.

    I recommend for this task use thread safe cache (for example ConcurrentHashMap) associate with users. It will be simpler for understanding and thread safe. If you want use ThreadLocal you need to clarify and minimize his lifecycle in your application.

    0 讨论(0)
  • 2021-01-26 09:20

    On your second question: clear thread local in the same filter in which you set it.

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        boolean contextSetViaThreadLocal = false;
        if (authentication != null && authentication.isAuthenticated()) {
            contextSetViaThreadLocal = true;
            // here we set context
        }
        // immediately after the conditional context store
        try {
            filterChain.doFilter(request, response);
        } finally {
            if (contextSetViaThreadLocal) {
                // clear the context
            }
        }
    
    0 讨论(0)
  • 2021-01-26 09:20

    you should clear context once after request is completed.

    try {
        filterChain.doFilter(request, response);
    }
    finally {
        // remove context here
    }
    
    0 讨论(0)
  • 2021-01-26 09:25

    it's single threaded unless you purposely initiate child threads. in such case use InheritableThreadLocal to store information.

    0 讨论(0)
提交回复
热议问题