SpringSession(springboot、redis和session整合)
官网:https://docs.spring.io/spring-session/docs/2.5.0/reference/html5/#samples
1、导入依赖
<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>
2、编写application.yml配置文件
spring:
redis:
host: 192.168.10.123
port: 6379
session:
store-type: redis
timeout: 30m
3、配置类SessionConfig.java
可以不用配置,根据实际情况配置
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;
@Configuration
public class SessionConfig {
@Bean
public CookieSerializer cookieSerializer(){
DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
cookieSerializer.setDomainName("mall.com");
cookieSerializer.setCookieName("SESSION");
return cookieSerializer;
}
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
4、主启动类增加注解:@EnableRedisHttpSession
5、使用
在不同服务中:存入数据和取数据,都需以上四个步骤
public viod loginPage(HttpSession session){
public static final String LOGIN_USER = "loginUser";
session.setAttribute(LOGIN_USER,data);
session.getAttribute(LOGIN_USER);
}
${session.loginUser}
6、其他借鉴
https://www.yuque.com/zhangshuaiyin/guli-mall/dno05u
|