微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Spring Cache缓存Java 8可选

我有一个方法

@Cacheable(key = "#jobId")
public Optional

当我尝试检索缓存的项目时,我收到以下异常:

2016-01-18 00:01:10 ERROR [trace=,span=] http-nio-8021-exec-2 [dispatcherServlet]:182 – Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing Failed; nested exception is 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 [java.util.Optional]] with root cause
java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [java.util.Optional]

最佳答案
Spring支持缓存可选.问题是您的Redis序列化程序(可能是JdkSerializationRedisSerializer).它使用基于Java的序列化,要求类可以序列化.您可以通过将RedisCacheManager配置为使用没有此限制的其他序列化程序来解决此问题.例如,您可以使用Kryo(com.esotericsoftware:kryo:3.0.3):

@Bean
RedisCacheManager redisCacheManager (RedistemplatedisOperations) {
    // redisOperations will be injected if it is configured as a bean or create it: new Redistemplate()...
    redisOperations.setDefaultSerializer(new RedisSerializerdobject(output,o);
            } finally {
                kryoPool.release(kryo);
                output.close();
            }

            return output.toBytes();
        }

        @Override
        public Object deserialize(byte[] bytes) throws SerializationException {
            if(bytes.length == 0) return null;

            Kryo kryo = kryoPool.borrow();
            Object o;
            try {
                o = kryo.readClassAndobject(new ByteBufferInput(bytes));
            } finally {
                kryoPool.release(kryo);
            }
            return o;
        }
    });

    RedisCacheManager redisCacheManager = new RedisCacheManager(redisOperations);
    redisCacheManager.setCachePrefix(new DefaultRedisCachePrefix("app"));
    redisCacheManager.setTransactionAware(true);
    return redisCacheManager;
}

请注意,这只是一个例子,我没有测试这个imeplementation.但我在生产中使用Kryo序列化程序以相同的方式使用Spring进行redis缓存.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐