Stateless session

Keywords: Java Redis Session Tomcat

One, What?

When a user accesses a system, it is "nonexistent" session, which disconnects and connects the system at the first visit. In this case, it is generally necessary to control in the background to maintain the relationship between the user and the system. Since Tomcat server can't do it, we can consider redis.

Two, Why?

Benefits of Redis-session

  1. It's easy to expand, and it's quite convenient when a single application expands into a cluster.
  2. Easy access authentication

Three, How?

1. When a user registers or logs in, save a unique Token to redis

String uniqueToken = UUID.randomUUID().toString();
redis.set(USER_REDIS_SESSION+":"+userModel.getId(), uniqueToken, 1000 * 60 * 30);

2. When the user needs to do some operations (such as uploading files, modifying personal information, etc.), the user can be authenticated by the interceptor.

@Autowired
    public RedisOperator redis;
    public static final String USER_REDIS_SESSION = "user-redis-session";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        String userToken = request.getHeader("userToken");
        if(StringUtils.isNoneBlank(userId) && StringUtils.isNoneBlank(userToken)){
            String uniqueToken = redis.get(USER_REDIS_SESSION + ":" + userId);
            if(StringUtils.isEmpty(uniqueToken) && StringUtils.isBlank(uniqueToken)){
                //userToken is out of date in redis and needs to be logged in again
                System.out.println("Please login.");
                returnErrorResponse(response,IMoocJSONResult.errorTokenMsg("Please login."));
                return false;
            }else{
               if(!uniqueToken.equals(userToken)){
                   //userToken has been modified to indicate that other people are logged in, which allows you to control that only one person can log in.
                   System.out.println("Accounts were crowded out...");
                   returnErrorResponse(response,IMoocJSONResult.errorTokenMsg("Accounts were crowded out..."));
                   return false;
               }
            }
        }else{
            //The message header does not have userId and userToken to indicate that the user is not logged in.
            System.out.println("Please login.");
            returnErrorResponse(response,IMoocJSONResult.errorTokenMsg("Please login."));
            return false;
        }
        return true;
    }
    
    ..........
    ..........
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(miniInterceptor()).addPathPatterns("/user/**")
                                                  .addPathPatterns("/bgm/**")
                                                  .addPathPatterns("/video/userLike","/video/userUnLike","/video/saveComment")
                                                  .addPathPatterns("/video/upload","/video/uploadCover")
                                                  .excludePathPatterns("/user/queryPublisher");
        WebMvcConfigurer.super.addInterceptors(registry);
    }

Posted by SieRobin on Sun, 07 Apr 2019 13:48:30 -0700