当前位置:网站首页>Record context information through ThreadLocal (record user information to realize global operation)

Record context information through ThreadLocal (record user information to realize global operation)

2022-06-21 07:24:00 In a flash

ThreadLocal A copy of the variable is provided for each thread , And variables are valid throughout the life cycle of the thread , It forms the isolation between threads , Only the same thread can manipulate variables , It's a kind of ” Space for time ” In the form of , Can be used to record some context data .

ThreadLocal Through internal Map To store copies of variables for each thread ,map Of key Namely threadLocal,value It's us set The value of , Every time a thread is in get When , All take values from their own variables , So it must be 不 There are thread safety issues .
Use ThreadLocal after , Be sure to pay attention to manual remove() Otherwise, it will cause OOM abnormal .

Scenario as follows :

  • Record each request for user information

ThreadLocal Code :

public class RequestHolder {
    

    private static final ThreadLocal<SysUser> userHolder = new ThreadLocal<SysUser>();


    public static void setUser(SysUser sysUser) {
    
        userHolder.set(sysUser);
    }

    public static SysUser getUser() {
    
        return userHolder.get();
    }

    public static void remove() {
    
        userHolder.remove();
    }
}

Application process :
The following process sections use Pseudo code Express
1、 Interceptors get user information
2、 It was recorded that ThreadLocal in
3、 Use through get() Method gets value

// 1、 Interceptors get user information 
// 2、 It was recorded that ThreadLocal in 
@Component
public class AuthenticationHandlerInterceptor implements HandlerInterceptor {
    

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
        log.debug(" Enter the interceptor ,URL:{}", request.getServletPath());

        //  Add user global information 
        RequestHolder.setUser(userInfo);
        return true;
    }
    ....
    ....
}

// 3、 Use through get() Method gets value 
@RestController
@RequestMapping
public class Controller {
    
   .....
    @GetMapping("/test")
    public String test() {
    
    	//  from ThreadLocal get data 
    	RequestHolder.getUserId();
        return " Successful visit ";
    }
   .....
}
原网站

版权声明
本文为[In a flash]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221515474391.html