SpringBoot整合redis把用戶登陸信息存入redis

首先引入redis的jai包redis

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

在userserviceimpl引用springboot自帶的StringRedisTemplatespring

@Autowired
private StringRedisTemplate stringRedisTemplate;
在userserviceimpl中經過usermapper查詢到用戶名和密碼等用戶信息後
 
若是user != null ,把user實體類轉換成json格式,redis是key/value格式,保證數據惟一性,因此key用uuid作key,user作value,確保惟一性
 
插入到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獲取的時候json

@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;
    }
相關文章
相關標籤/搜索