Redis - How to configure custom conversions

前端 未结 4 1276
温柔的废话
温柔的废话 2021-01-17 19:30

In spring-data-redis, How do we need configure custom converters that can be auto-wired/injected from Spring boot application or configuration.

I read about @R

4条回答
  •  攒了一身酷
    2021-01-17 20:08

    Tested with spring-boot-starter-data-redis:2.0.4.RELEASE.

    I was facing a problem where my OffsetDateTime properties of my @RedisHash entity were not being stored when using CrudRepository.

    The problem was that Jsr310Converters does not have a converter of OffsetDateTime.

    To solve this, I created a reading converter:

    @Component
    @ReadingConverter
    public class BytesToOffsetDateTimeConverter implements Converter {
        @Override
        public OffsetDateTime convert(final byte[] source) {
            return OffsetDateTime.parse(new String(source), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        }
    }
    

    and writing converter:

    @Component
    @WritingConverter
    public class OffsetDateTimeToBytesConverter implements Converter {
        @Override
        public byte[] convert(final OffsetDateTime source) {
            return source.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME).getBytes();
        }
    }
    

    And registered a RedisCustomConversions bean in the configuration:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.core.convert.RedisCustomConversions;
    import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
    
    import java.util.Arrays;
    
    @Configuration
    @EnableRedisRepositories
    public class RedisConfiguration {
    
        @Bean
        public RedisCustomConversions redisCustomConversions(OffsetDateTimeToBytesConverter offsetToBytes,
                                                             BytesToOffsetDateTimeConverter bytesToOffset) {
            return new RedisCustomConversions(Arrays.asList(offsetToBytes, bytesToOffset));
        }
    
    }
    

提交回复
热议问题