SpringCloud分布式Session共享同步

通常情况下,Tomcat、Jetty等Servlet容器,会默认将Session保存在内存中。如果是单个服务器实例的应用,将Session保存在服务器内存中是一个非常好的方案。但是这种方案有一个缺点,就是不利于扩展。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名、网络空间、营销软件、网站建设、麻栗坡网站维护、网站推广。

目前越来越多的应用采用分布式部署,用于实现高可用性和负载均衡等。那么问题来了,如果将同一个应用部署在多个服务器上通过负载均衡对外提供访问,如何实现Session共享?

实际上实现Session共享的方案很多,其中一种常用的就是使用Tomcat、Jetty等服务器提供的Session共享功能,将Session的内容统一存储在一个数据库(如MySQL)或缓存(如redis)中。

下面我们将在springcloud微服务项目中,使用redis实现简单高效的session共享。官网:www.fhadmin.org

  • eureka-server:注册中心

  • springcloud-session-redis:业务session所在项目

  • springcloud-session-zuul:路由网关

springcloud-session-redis项目

新建一个spring boot项目,命名springcloud-session-redis

pom



    4.0.0

    com.carry
    springcloud-session-redis
    0.0.1-SNAPSHOT
    jar

    springcloud-session-redis
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Finchley.SR1
    

    
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.springframework.session
            spring-session-data-redis
        
        
            org.apache.commons
            commons-pool2
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        

    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


配置文件

在application.yml中加入redis、eureka、port等配

server:
  port: 8090
spring:
  application:
    name: service-session-redis
  redis:
    host: 192.168.68.100
    port: 6379
    password: 123456
    timeout: 6000ms
    lettuce:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0
    database: 0
eureka:
  client:
    serviceUrl:
      defaultZone: http://admin:123456@localhost:8761/eureka/
management: 
  endpoints:
    web:
      exposure: 
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: "*"

Redis Session配置类

package com.carry.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {

}

控制层Controller中添加测试方法

package com.carry.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class UserManagementController {

    /**
     * redis sesion共享
     * 
     * @param request
     * @return
     */
    @GetMapping("/getUser")
    public String getUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (StringUtils.isEmpty(username)) {
            username = "testSessionRedis|" + System.currentTimeMillis();
            session.setAttribute("username", username);
        }
        System.out.println("访问端口:" + request.getServerPort());
        return username;
    }
}

springcloud-session-zuul项目

新建springboot项目,命名springcloud-session-zuul

POM依赖配置



    4.0.0

    com.carry
    springcloud-session-zuul
    0.0.1-SNAPSHOT
    jar

    springcloud-session-zuul
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Finchley.SR1
    

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


配置文件

server:
  port: 1100
spring:
  application:
    name: service-session-zuul
zuul: 
  ignoredServices: '*' #忽略所有未配置的service
  host:
    connect-timeout-millis: 20000
    socket-timeout-millis: 20000
  routes:
    redis-session-service: 
      path: /user-session/**
      serviceId: service-session-redis
      sensitiveHeaders: "*" 
ribbon: #ribbon负载均衡参数配置
  ReadTimeout: 5000
  ConnectTimeout: 5000
eureka:
  client:
    serviceUrl:
      defaultZone: http://admin:123456@localhost:8761/eureka/

启动类

package com.carry;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableEurekaClient
@SpringBootApplication
@EnableZuulProxy
public class SpringcloudSessionZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudSessionZuulApplication.class, args);
    }
}

网页名称:SpringCloud分布式Session共享同步
浏览路径:http://pwwzsj.com/article/goscso.html