整合SpringSession
使用SpringSession的目的是来解决分布式session不同步不共享的问题,其实就是为了让登录信息在订单微服务里共享
注意:由于这里使用springsession的用的类型是redis,所以这springsession和redis都要一起加入依赖和配置(所以session会被存到Redis缓存中)
(1)导入依赖
<!-- 整合springsession 来解决分布式session不同步不共享的问题--> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <!-- 整合redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
(2)在application.properties配置文件里配置springsession
#配置springsession spring.session.store-type=redis server.servlet.session.timeout=30m #配置redis的ip地址 spring.redis.host=192.168.241.128
(3)在config配置中加入springSession配置类
package com.saodai.saodaimall.order.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.session.web.http.CookieSerializer; import org.springframework.session.web.http.DefaultCookieSerializer; /** * springSession配置类(所有要使用session的服务的session配置要一致) */ @Configuration public class GulimallSessionConfig { /** * 配置session(主要是为了放大session作用域) * @return */ @Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); //放大作用域 cookieSerializer.setDomainName("saodaimall.com"); cookieSerializer.setCookieName("SAODAISESSION"); return cookieSerializer; } /** * 配置Session放到redis存储的格式为json(其实就是json序列化) * @return */ @Bean public RedisSerializer<Object> springSessionDefaultRedisSerializer() { return new GenericJackson2JsonRedisSerializer(); } }
(4)在启动类上添加@EnableRedisHttpSession注解
package com.saodai.saodaimall.order; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * 订单服务启动类 */ @EnableFeignClients @EnableRedisHttpSession @EnableDiscoveryClient @SpringBootApplication public class SaodaimallOrderApplication { public static void main(String[] args) { SpringApplication.run(SaodaimallOrderApplication.class, args); } }