一、Session 共享
在分布式微服务中,经常会部署集群服务,如果我们在8001服务登陆了,如果使用SpringSessing在8002服务、8003服务的时候就不需要再次登陆啦。
导入依赖
<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>
yml
配置springsession和redis配置
spring:
session:
store-type: redis
redis:
host: 116.62.13.104
启动类
使用@EnableRedisHttpSession
注解开启session共享
如果连接不上redis,设置以下配置并重启
redis-cli
CONFIG SET protected-mode no
主启动类添加@EnableSpringHttpSession注解
@EnableEurekaClient
@SpringBootApplication
//Fegin
@EnableFeignClients
//开启session共享
@EnableSpringHttpSession
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class);
}
@Bean
public BCryptPasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}
}
测试
在8001服务登录以后
Redis 中的用户信息
8002服务不需要登陆就可以执行
8003服务不需要登陆就可以执行
如果8001退出登录了以后
再次调用8002、8003的方法就会被踢出
Bug 使用Fegin调用Session失效
8001登陆认证
使用Fegin负载均衡调用Dept8002、Dept8003
原因:
微服务使用feign相互之间调用时,存在session丢失
解决方法:
编写一个拦截器来实现Header的传递,也就是需要实现RequestInterceptor
接口。
com.lsh.service
是Fegin调用其他服务的包路径
@Configuration
@EnableFeignClients(basePackages = "com.lsh.service")
public class FeignRequestIntercepter implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
//通过RequestContextHolder获取本地请求