SpringBoot開發案例之分佈式集羣共享Session

前言

在分佈式系統中,爲了提高系統性能,一般會對單體項目進行拆分,分解成多個基於功能的微服務,若是有條件,可能還會對單個微服務進行水平擴展,保證服務高可用。nginx

那麼問題來了,若是使用傳統管理 Session 的方式,咱們會遇到什麼樣的問題?redis

案例

這裏拿下單舉例,用戶小明在天貓上相中了一個的娃娃,以爲不錯,果斷購買,選尺寸,挑身高,而後確認選擇,趕忙提交訂單,而後就跳轉到了登陸頁面!小明表示很鬱悶,大寫的問號???spring

  • 小明進入娃娃頁面,此時請求經過代理服務發送到業務系統一。後端

  • 小明選尺寸,挑身高,此操做並無對後端服務發送請求。session

  • 小明提交訂單,此時請求經過代理服務發送到業務系統二,然鵝,二系統此時並無查詢到小明的登陸信息,就被無情的跳轉到登陸頁了。app

方案

HttpSession 默認使用內存來管理 Session,一般服務端把用戶信息存儲到各自的 Jvm 內存中。因此小明下單的時候找不到登陸信息,那麼我麼何不把用戶信息集中存儲!?分佈式

爲了測試效果,這裏咱們搭建一個演示案例,項目涉及 SpringBoot、spring-session、redis、nginx 等相關組件。spring-boot

pom.xml引入依賴:微服務

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

配置 redis 參數,軟件自行安裝:性能

## redis
#session存儲類型
spring.session.store-type=redis
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=3000

簡單的用戶登陸實現,省略部分代碼:

@RequestMapping(value="login",method=RequestMethod.POST)
public Result login(String username,String password,HttpServletRequest request,HttpServletResponse response) throws Exception {
        SysUser user = userService.getUser(username);
        if(user==null) {
            return Result.error("用戶不存在");
        }else {
            if(user.getPassword().equals(password)) {
                request.getSession().setAttribute("user", user);
                return Result.ok();
            }else {
                return Result.error("密碼錯誤");
            }
        }
}

配置代理實現,基於 Nginx:

server {
        listen       80;
        server_name  blog.52itstyle.vip;
        location / {
            proxy_pass http://192.168.1.2:8080; 
        }
        location /cart {
             proxy_pass http://192.168.1.3:8080$request_uri;
        }
       location /order {
             proxy_pass http://192.168.1.4:8080$request_uri;
        }
  }

配置成功後登陸系統,在 redis 中查詢用戶信息:

127.0.0.1:6379> keys *
1) "spring:session:expirations:1562577660000"
2) "spring:session:sessions:1076c2bd-95b1-4f23-abd4-ab3780e32f6f"
3) "spring:session:sessions:expires:1076c2bd-95b1-4f23-abd4-ab3780e32f6f"

小結

這樣,小明就能夠開心的買娃娃了!

相關文章
相關標籤/搜索