天天看點

(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五

首先,導包。

在pom.xml檔案裡面加入以下:

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

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

jar包不做多解釋了,看那個artifactId的内容應該能知道幹啥的。

然後是yml檔案:

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    jedis.pool.max-idle: 100
    jedis.pool.max-wait: -1ms
    jedis.pool.min-idle: 2
    timeout: 2000ms      

是的,很精簡。

然後是,到你的RedisConfig檔案上面,開啟redis的session關聯注解(其實不用這個注解也是沒問題的,後面自己可以去除看看。)

@EnableRedisHttpSession(maxInactiveIntervalInSeconds=60) 這邊是設定存入redis裡面的值的過期時間。

預設不設定的話,是1800秒即30分鐘。

@EnableRedisHttpSession      

如:

(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五

OK,我們開始共享session咯!

在controller檔案裡面寫2個方法吧,

@GetMapping("/setSessionValue")
public String setredisResult(HttpServletRequest request){
    request.getSession().setAttribute(request.getSession().getId(), "---測試資料---"+request.getRequestURL());

    System.out.println(request.getSession().getId());
    return "set成功,已經存入session域且redis裡面也會有值";
}

@GetMapping("/getSessionValue")
public String redisResult(HttpServletRequest request) {
    System.out.println(request.getSession().getId());
    String value = String.valueOf(request.getSession().getAttribute(request.getSession().getId()));
    
    return "取值成功         :"+value;
}      

先運作第一個, 如下:

(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五

控制台列印出sessionid值:

(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五

然後再瞟一眼redis資料庫,是的,沒錯,可以看到redis也存儲了這個session會話的相關資訊。 (TTL是過期時間)

(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五
(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五

然後通路下第二個接口,可以看到根據sessionid作為Key去session域是能正常擷取值的,

(Redis使用系列) Springboot 使用Redis+Session實作Session共享 ,簡單的單點登入 五

好了,redis實作session共享到此其實已經完畢了!

有人可能會有疑問,怎麼展現共享了? 這時候,你如果實作負載均衡,開啟兩個tomcat伺服器,不同端口,然後用通過浏覽器通過不同端口去通路,你會發現,通過request.getSession().getId()拿出來的sessionid是一樣一樣的!

那麼接下來簡單介紹下,使用這個唯一id來實作單點登入:

@GetMapping("/userLogin")
    public String setRedisResult(HttpServletRequest request){

        //第一次登入

        //1. 取出當期用戶端的sessionId
        String sId=request.getSession().getId();
        //2. 查詢該sessionId 是否存在于redis
        boolean exists = redisUtils.exists(sId);

        if (!exists){
            //2.1未登入過,進行使用者資訊的校驗
            //如果通過後,寫入session域進行共享,即使是負載不同端口,sessionId不會發生變化
            request.getSession().setAttribute(sId, "login success");
            redisUtils.setWithTime(sId,"login success",1000);
            return "success login!";

            //如果不通過,那麼傳回登入頁面,省略
        }else {
            //2.2 已經登入過,則存入redis中重新整理過期時間,再直接傳回成功頁面
            redisUtils.setWithTime(sId,"login success",1000);
            return " yes,you are allow!";
        }

    }

    @GetMapping("/userLoginOut")
    public String userLoginOut(HttpServletRequest request){

        String sId=request.getSession().getId();
        redisUtils.remove(sId);
        return "login out!";
    }      

ps:代碼裡使用到的工具類RedisUtils

可以看到以上情況其實單純使用redis配合sesionid共享後就能完成單點登入;

//登入接口
    @GetMapping("/userLogin")
    public String setRedisResult(HttpServletRequest request, HttpServletResponse response){
        
        //第一次登入

        //1. 取出當期用戶端的sessionId
        String sId=request.getSession().getId();

        String cookies = getCookies(request);

        if (cookies==null || cookies.equals("")){

            System.out.println("沒有登入過,準備進行登入!");
            //執行登入邏輯

            //寫入cookie
            writeLoginToken(response,sId); //這裡設定cookie的過期時間應當與redis設定的時間且與session失效時間保持一緻
            //寫入redis
            redisUtils.setWithTime(sId,"userInfo",1000);
            System.out.println("登入成功!");
            return "success login!";
        }else{

            boolean exists = redisUtils.exists(cookies);
            if (exists){

                System.out.println("已經登入過,正常登入!");
                return " yes,you are allow!";
            }else {

                return "資訊異常不允許登入";
            }
        }



    }      
/**
     * 擷取浏覽器存入
     * @param request
     * @return
     */
    public  String getCookies(HttpServletRequest request){
        //HttpServletRequest 裝請求資訊類
        //HttpServletRespionse 裝相應資訊的類

        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("SESSION_ID")){
                    return cookie.getValue();
                }
            }
        }

        return  null;
    }

    /**
     *設定浏覽器cookie
     * @param response
     * @param token
     */
    public static void writeLoginToken(HttpServletResponse response,String token){
        Cookie ck = new  Cookie("SESSION_ID",token);
        //設定cookie的域
//        ck.setDomain("jc.test.com");
//        //代表設在根目錄
//        ck.setPath("/");
        //防止腳本讀取
        ck.setHttpOnly(true);
        //機關是秒,設定成-1代表永久,如果cookie不設定maxage的話,cookie就不會寫入硬碟,寫在記憶體中,隻在目前頁面有效
        ck.setMaxAge(1000);
        response.addCookie(ck);
    }      

就到此吧。

繼續閱讀