springboot combined with redis (save user login information)

One: Import the package:

 <dependency>			<groupId>org.springframework.boot</groupId>			<artifactId>spring-boot-starter-data-redis</artifactId></dependency>

1.1 Configuration file:

.yml format:

redis:  host:  port: 6379

Two: Combine StringRedisTemplate to  achieve development/

2.1 Implement cookie value transfer, because the session value will change during cluster development, and the session value of machine A and machine B must change. Therefore, it is necessary to plant the cookie value to ensure that the user will not appear after logging in , and log in to the A machine can only be used in the A machine. Once you request to transfer to machine B, you must log in again.

Write cookie

public static void writeLoginToken(HttpServletResponse response,String token){        Cookie ck = new Cookie(COOKIE_NAME,token);        ck.setPath("/");        ck.setHttpOnly(true);        ck.setMaxAge(Redisconstant.EXPIRE); //保存时间        log.info("write cookie name:{} , cookie vlaue: {}",ck.getName(),ck.getValue());        response.addCookie(ck);

Read cookie

public static String readLoginToken(HttpServletRequest request){        Cookie[] cks = request.getCookies();        if (cks != null){            for (Cookie ck : cks){                log.info("read cookie name:{} , cookie value:{}",ck.getName(),ck.getValue());                if (StringUtils.equals(ck.getName(),COOKIE_NAME)){                    return ck.getValue();                }            }        }        return null; 

Delete Cookie (for logout)

public static void delLoginToken(HttpServletResponse response,HttpServletRequest request){        Cookie[] cks = request.getCookies();        if (cks != null){            for (Cookie ck : cks){                if (StringUtils.equals(ck.getName(),COOKIE_NAME)){                    ck.setPath("/");                    ck.setMaxAge(0); //0 = del                    log.info("del cookie name : {} ,cookie vlaue: {}",ck.getName(),ck.getValue());                    response.addCookie(ck);                    return;                }            }        }

After obtaining the cookie value, just put the cookie value into redis and set the same time value to realize the cluster login.

String token = session.getId();        Integer expire = Redisconstant.EXPIRE;        //设置 token 至 redis        redisTemplate.opsForValue().set(String.format(Redisconstant.TOKEN_PREFIX,token),openid,expire, TimeUnit.SECONDS);         //设置 token 至 cookie        CookieUtil.writeLoginToken(httpServletResponse,token);

2.3 Combined use:

@Autowiredprivate StringRedisTemplate redisTemplate;
@GetMapping("/login")    public ModelAndView login(@RequestParam("openid") String openid,   //ModelAndView                              HttpServletResponse httpServletResponse,                              Map<String,Object> map, HttpSession session){        // 数据库匹配        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenId(openid);  //通过关键字 查询用户        if (sellerInfo == null){   // 判断用户是否存在            map.put("msg",ResultEnum.LOGIN_FAIL.getMessage());            map.put("url","你的页面地址");            return new ModelAndView("/common/error");        }//        String token = UUID.randomUUID().toString();        String token = session.getId();   //获取登录 token        Integer expire = Redisconstant.EXPIRE;  //设置时间        //设置 token 至 redis        redisTemplate.opsForValue().set(                //String TOKEN_PREFIX = "token_%s";                String.format(Redisconstant.TOKEN_PREFIX,token) // key                ,openid  //关键字  value                ,expire,  // 时间                TimeUnit.SECONDS);  //格式         //设置 token 至 cookie        CookieUtil.writeLoginToken(httpServletResponse,token);        return new ModelAndView("你的页面地址 如 http://login");

2.4 Logout:

@GetMapping("/logout")    public ModelAndView logout(HttpServletRequest request,                       HttpServletResponse response,                       Map<String,Object> map){        //cookie查询        String token = CookieUtil.readLoginToken(request);        if (StringUtils.isNotEmpty(token)){            // 清除 redis            redisTemplate.opsForValue().getOperations().delete(String.format(Redisconstant.TOKEN_PREFIX,token));             // del cookie            CookieUtil.delLoginToken(response,request);        }        map.put("msg",ResultEnum.LOGOUT_SUCCESS.getMessage());        map.put("url","你的页面地址");        return new ModelAndView("common/success",map);     }