1.相关介绍
对于session无法跨服务, 跨域名使用的问题, 我们可以使用SpringSession将session保存在中间件中(比如redis), 从而实现了session的共享.
浏览器cookie保存一个session的key, 如图就是叫jsessionid, 这个key就对应着redis中的session, 用来标识一个用户
2.整合步骤
1.添加依赖
<!--1、整合SpringSession完成session共享问题, 我的SpringBoot版本为2.1.8.RELEASE-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.编写配置
application.properties
spring.redis.host=192.168.56.103
spring.redis.port=6379
spring.session.store-type=redis
server.servlet.session.timeout=30m
GulimallSessionConfig
package com.atguigu.gulimall.auth.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;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@EnableRedisHttpSession //整合redis作为session存储
@Configuration
public class GulimallSessionConfig {
@Bean
public CookieSerializer cookieSerializer(){
DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
cookieSerializer.setDomainName("gulimall.com");
cookieSerializer.setCookieName("GULISESSION");
return cookieSerializer;
}
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
3.具体使用
@PostMapping("/login")
public String login(UserLoginVo vo,RedirectAttributes redirectAttributes,
HttpSession session){
//远程登录
R login = memberFeignService.login(vo);
if(login.getCode()==0){
MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
});
//看这里, 成功放到session中
session.setAttribute(AuthServerConstant.LOGIN_USER,data);
return "redirect:http://gulimall.com";
}else {
Map<String,String > errors = new HashMap<>();
errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
redirectAttributes.addFlashAttribute("errors",errors);
return "redirect:http://auth.gulimall.com/login.html";
}
}
3.运行测试
另一个服务的前端使用session