Spring Data Redis的自定义@Id类

时间:2018-10-21 07:26:24

标签: spring-data-redis

我正在尝试转换/序列化模型类的@Id字段(不是字符串),但始终收到此错误。自定义ID类仅用冒号连接两个值,例如aaaa:2345

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [MyIdClass] to type [byte[]]

这是我的模型课。

@RedisHash("alert")
public class MyClass implements Serializable
{
    public static class MyIdClass
    {
        public String userId;
        public Long sessionExpiry;

        public MyIdClass()
        {
        }

        public MyIdClass(String id, Long ex)
        {
            userId = id;
            sessionExpiry = ex;
        }
    }

    public static class MyIdClassSerializer implements RedisSerializer<MyIdClass>
    {
        @Nullable
        @Override
        public byte[] serialize(@Nullable MyIdClass uid) throws SerializationException
        {
            return String.format("%s:%d", uid.userId, uid.sessionExpiry).getBytes();
        }

        @Nullable
        @Override
        public MyIdClass deserialize(@Nullable byte[] bytes) throws SerializationException
        {
            String[] t = new String(bytes).split(":");
            return new MyIdClass(t[0], Long.parseLong(t[1]));
        }
    }

    @Component
    @ReadingConverter
    public static class MyIdClassReader implements Converter<byte[], MyIdClass>
    {

        @Nullable
        @Override
        public MyIdClass convert(byte[] source)
        {
            String[] t = new String(source).split(":");
            return new MyIdClass(t[0], Long.parseLong(t[1]));
        }
    }

    @Component
    @WritingConverter
    public static class MyIdClassWriter implements Converter<MyIdClass, byte[]>
    {

        @Nullable
        @Override
        public byte[] convert(MyIdClass uid)
        {
            return String.format("%s:%d", uid.userId, uid.sessionExpiry).getBytes();
        }
    }

    /**
     * User ID
     * Key := 'alert:' userId ':' sessionExpiry
     */
    @Id
    public MyIdClass id;

    public String value;
}

这是我配置RedisTemplate的方式。

@Bean("redisTemplateActivityAlert")
public RedisTemplate<ActivityAlert.UserIdExpiry, ActivityAlert> redisTemplateActivityAlert()
{
    RedisTemplate<ActivityAlert.UserIdExpiry, ActivityAlert> template = new RedisTemplate<>();
    template.setConnectionFactory(jedisConnectionFactory());
    template.setKeySerializer(new ActivityAlert.UserIdExpirySerializer());
    template.setHashKeySerializer(new ActivityAlert.UserIdExpirySerializer());
    return template;
}

我还阅读了其他有关配置ConversionServiceTypeConverter的文章,但并没有走太远。

1 个答案:

答案 0 :(得分:0)

将此Bean添加到您的RedisConfiguration中:

    @Bean
    public RedisCustomConversions redisCustomConversions(MyIdClassReader  myIdClassReader , MyIdClassWriter  myIdClassWriter ) {
        return new RedisCustomConversions(Arrays.asList(myIdClassWriter,myIdClassReader)); 
    }