shiro org.apache.shiro.session.mgt.SimpleSession物件 反序列化失敗

成佛在西天發表於2024-05-31

問題描述

org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized field "valid" (class org.apache.shiro.session.mgt.SimpleSession), not marked as ignorable (9 known properties: "attributeKeys", "timeout", "startTimestamp", "expired", "lastAccessTime", "host", "id", "stopTimestamp", "attributes"])

本質

redis在儲存SimpleSession物件時,不知為什麼多儲存了一個valid欄位,導致無法反序列化

shiro org.apache.shiro.session.mgt.SimpleSession物件 反序列化失敗

解決方案

方案一

redis序列化時,對key採用字串序列化,對value採用預設jdk序列化方式

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;


@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

        //常用<String,Object>
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //設定預設序列化方式 可以是:Jackson2JsonRedisSerializer GenericJackson2JsonRedisSerializer
//        redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());

        // 設定key以字串序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        return redisTemplate;
    }
}

最終效果

shiro org.apache.shiro.session.mgt.SimpleSession物件 反序列化失敗

相關文章