spring boot项目中session共享

session共享原理:
在分布式环境下 实现session共享,Session信息存储在Redis中
1.加入依赖

<!-- springsession框架依赖 -->
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-core</artifactId>
		</dependency>
		<!-- springsession与redis的整合依赖 -->
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
		</dependency>
		<!-- springboot与redis的整合依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

2.修改配置文件,添加redis地址

spring: 
  redis:
    host: localhost
    port: 6379

3.在主程序上添加注解

@EnableRedisHttpSession

4.创建一个配置文件,以来对付同域名,不同项目实现session或者不同域名,同一个根域名实现session共享:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;
import org.springframework.session.web.http.DefaultCookieSerializer;

@SpringBootConfiguration
public class SpringSessionConfig {
	@Autowired
	private DefaultCookieSerializer cookieSerializer;
	@Bean
	public RedisHttpSessionConfiguration  redisHttpSessionConfiguration() {
		cookieSerializer.setCookiePath("/");
		cookieSerializer.setDomainName("web.com");
		RedisHttpSessionConfiguration redisConfiguration = new RedisHttpSessionConfiguration();
		redisConfiguration.setCookieSerializer(cookieSerializer);
		return redisConfiguration;
	}
}

你可能感兴趣的:(开发路上不会写的代码)