ThreadLocal obtains user information globally

Scenario requirements: Although after logging in, the front end can get the jwt returned by me, and then use it to maintain the login status and obtain information. Then when the interface is called, the information is passed to me for various operations.
But for various reasons, I need to easily get some basic information of the current user in any method during the execution of the operation .
Instead of purely relying on the front end to pass the value.
Because not all methods can get jwt, if there is no request header as a parameter.
I envisioned a simple way to implement it, that is, when the request passes jwtFilter, while obtaining jwt, store the parsed user information in ThreadLocal.
If ThreadLocal is used, it can be used as a global parameter in any method in the process of user invocation, and the desired information can be obtained at any time.

 

 

1. After successful login, store the user information in the redis cache

The pseudo code is as follows

 @RequestMapping("/login")
    public Map<String,String> login(String name){
        Map<String,Object> result = new HashMap<>();
        result.put(ExecutionContext.USER_ID,name);
        result.put(ExecutionContext.USER_NAME,name);
        result.put(ExecutionContext.ACCESS_TOKEN,name);
        //存储用户信息到redis中 key值Token  value是用户信息
        RMap<String, String> map = redissonClient.getMap(name);

Guess you like

Origin blog.csdn.net/zsj777/article/details/95479583