一:首先 引入相应架包(装上redis 服务)
pom.xml 添加如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
二,配置文件yml添加如下(或者采用.properties方式添加):
redis:
host: 192.168.1.11
port: 6379
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
database: 0
# Redis服务器连接密码(默认为空)
password:
# 连接池最大连接数(使用负值表示没有限制)
# 连接超时时间(毫秒)
timeout: 0
pool:
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
三,启动类添加注解@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60*30):
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@SpringBootApplication
@ServletComponentScan
@Configuration
@EnableDiscoveryClient
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60*30)
public class ProviderBdApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(ProviderBdApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
logger.info("启动加载自定义的ServletInitializer");
return application.sources(ProviderBdApplication.class);
}
}
四, 存取sesion
经过以上步骤 ,就实现了session 共享功能,
存入session:request.getSession().setAttribute("loginUser", User);
//根据id 获取 session
@Resource(name="sessionRepository")
private SessionRepository<ExpiringSession> sessionRepository;
Strign sessionId = session.getId();//此处session 可以根据传 入参数获取
ExpiringSession session = sessionRepository.getSession(sessionId );// 根据sessionid 获取 session 同而实现共享
User user = session.getAttribute("loginUser");
java 技术交流群:317628801