zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

springboot 整合redis实现分布式session

2023-04-18 13:07:53 时间

版本

2.x

依赖

<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>

配置Session

@EnableRedisHttpSession(redisNamespace = "spring.session", maxInactiveIntervalInSeconds = 1800)

spring:
  session:
    redis:
      namespace: spring.session
    timeout: 1800

配置Redis连接

spring:
  redis:
    host: host
    port: port
    database:  database
    password: password

注意

如果session中保存自定义类型数据,类需实现Serializable接口,否则自定义类型序列化失败导致访问报错

org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [xxx.xxx.xxx] at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:96)