spring 获取并反序列化存储为单个字符串的对象列表

vuktfyat  于 2022-12-10  发布在  Spring
关注(0)|答案(1)|浏览(116)

例如,我有一个序列化的值,在Redis中以字符串的形式存储,它代表了UserAction对象的列表:

["java.util.ArrayList",[{"@class":"com.domain.UserAction","id":1,"name":"Login"},{"@class":"com.domain.UserAction","id":2,"name":"Logout"}]]

当我试图通过redisTemplate通过它的密钥(例如UserActionsCache)访问它时:

RedisTemplate<String, UserAction> redisTemplate;
redisTemplate.opsForValue().get(key);

它会抛出如下错误:

org.springframework.data.redis.serializer.SerializationException: Could not read JSON:
Could not resolve type id `com.domain.UserAction` as a subtype of `java.lang.Object`: no such class found

我尝试将redisTemplate更改为以下版本,但它有相同的问题:

RedisTemplate<String, List<UserAction>> redisTemplate;
RedisTemplate<String, ArrayList<UserAction>> redisTemplate;
RedisTemplate<String, Object> redisTemplate;

如何正确地访问值并将其反序列化为对象列表?
这是我的redisTemplate配置的一部分:

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connection-factory-ref="jedisConnFactory"
          p:keySerializer-ref="stringRedisSerializer"
          p:valueSerializer-ref="genericJackson2JsonRedisSerializer"
          p:hashKeySerializer-ref="stringRedisSerializer"
          p:hashValueSerializer-ref="genericJackson2JsonRedisSerializer"
    />
nimxete2

nimxete21#

你好我知道这是老问题,但你可以简单地重构你的redisTemplate
我不知道什么是Spring的等效豆定义,但我离开Spring Boot 。

@Bean
public RedisTemplate<String, List<UserAction>> redisTemplate() {

    final var redisTemplate = new RedisTemplate<String, List<UserAction>>();
    redisTemplate.setConnectionFactory(redisConnectionFactory());

    final var jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

    final var objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL,  JsonAutoDetect.Visibility.ANY);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
}

然后您可以像这样自动连接相关的bean。
RedisTemplate<String, List<UserAction>> redisTemplate
用法:
redisTemplate.opsForValue().get("key");
这一定有用

相关问题