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查詢到用戶名和密碼等用戶信息后
 
如果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獲取的時候

@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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM