通过spring-sesion 这个框架实现session的分布式,非常的简单方便。当我们需要session共享的应用,可以通过redis来实现,非常的简单方便。
代码地址
https://gitee.com/yellowcong/springboot-demo/tree/master/springboot-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>
配置application.properties
需要设定redis的配置信息
#session存储类型
spring.session.store-type=redis
#设置session超时时间
server.session.timeout=2000
#远程地址
spring.redis.host=192.168.100.11
#端口
spring.redis.port=6379
#密码信息
spring.redis.password=yellowcong
配置@EnableRedisHttpSession 注解
通过设置@EnableRedisHttpSession 这个注解,使用redis来管理session的服务
package com.yellowcong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@EnableRedisHttpSession
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
/**
* @author yellowcong <br>
* 创建日期:2018/02/05 设定首页
*/
@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 设定首页为index
registry.addViewController("/").setViewName("forward:/sample/home");
// 设定匹配的优先级
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
// 添加视图控制类
super.addViewControllers(registry);
}
}
}
测试访问
访问服务后,可以看到生成了sessionID,然后在redis的数据库中,也可以看到生成了这个id信息
nginx 多主机测试
我们使用nginx做代理,然后后端挂两个tomcat跑我们的程序,如果是以前没有配置分布式session,存储到redis中,就会有多个session的情况。
#8080 端口启动
nohup java -Dfile.encoding=utf-8 -jar -Dserver.port=8080 /data/app/springboot-session-0.0.1-SNAPSHOT.jar >/dev/null 2>&1 &
#8081 端口启动
nohup java -Dfile.encoding=utf-8 -jar -Dserver.port=8081 /data/app/springboot-session-0.0.1-SNAPSHOT.jar >/dev/null 2>&1 &
实现的访问效果,可以看到代理到了8080和8081 两个端口,session也是没有变化,springboot 很简单的就解决了session共享的问题。