SpringBoot整合redis把用户登录信息存入redis
首先引入redis的jai包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
在userserviceimpl引用springboot自带的StringRedisTemplate
@Autowired private StringRedisTemplate stringRedisTemplate;
在userserviceimpl中通过usermapper查询到用户名和密码等用户信息后
插入到redis后要在获取key的话要用到cookie了,把key存到cookie中,取的时候在cookie中取
//把user实体类转化成json格式 String userJoin = JSON.toJSONString(user); if (user != null) { //获取uuid String uuid = UUIDUtils.getUUID(); //创建cookie Cookie cookie = new Cookie("userCookie", uuid); response.addCookie(cookie); //把用户信息存入redis set(key,value,过期时长,过期格式) 设置三天过期 stringRedisTemplate.opsForValue().set("user" + "/" + uuid, userJoin, 3, TimeUnit.DAYS); return Msg.ok(""); } else { return Msg.failure("用户名或密码错误"); }
然后在usercontroller获取的时候
@RequestMapping(value = "/toMainPage") public ModelAndView toMainPage(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv; String struuid = null; //获取cookie里面的uuid Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase("userCookie")) { struuid = cookie.getValue(); } } if (struuid == null) { System.out.println("验证不通过"); System.out.println("UUID不存在"); } String userJson; try { //根据struuid,在redis中获取user信息 userJson = stringRedisTemplate.opsForValue().get("user" + "/" + struuid); JSONObject pa = JSONObject.parseObject(userJson); if ("管理员".equals(pa.getString("uRank")) && userJson != null) { mv = new ModelAndView("index"); mv.addObject("user", pa.getString("uName")); mv.addObject("id", pa.getString("id")); mv.addObject("uPwd", pa.getString("uPwd")); } else if ("普通用户".equals(pa.getString("uRank")) && userJson != null) { mv = new ModelAndView("pt_index"); mv.addObject("user", pa.getString("uName")); mv.addObject("id", pa.getString("id")); mv.addObject("uPwd", pa.getString("uPwd")); } else { mv = new ModelAndView("redirect:login"); } } catch (Exception e) { // TODO Auto-generated catch block mv = new ModelAndView("redirect:login"); } return mv; }