Redis - How to configure custom conversions

前端 未结 4 1274
温柔的废话
温柔的废话 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:16

    Try to implement this way.

    import java.sql.Timestamp;
    
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.data.convert.ReadingConverter;
    import org.springframework.stereotype.Component;
    
    
    @Component
    @ReadingConverter
    public class BytesToDateConverter implements Converter {
        @Override
        public Timestamp convert(final byte[] source) {
            String value = new String(source);
            return new Timestamp(Long.parseLong(value));
        }
    }
    

    and resister to the Bean.

    @Bean
        public MappingRedisConverter redisConverter(RedisMappingContext mappingContext,
                RedisCustomConversions customConversions, ReferenceResolver referenceResolver) {
    
             MappingRedisConverter mappingRedisConverter = new MappingRedisConverter(mappingContext, null, referenceResolver,
                        customTypeMapper());
            mappingRedisConverter.setCustomConversions(redisCustomConversions());
            return mappingRedisConverter;
        }
        
        @Bean
        public RedisTypeMapper customTypeMapper() {
            return new CustomRedisTypeMapper();
        }
        
        public RedisCustomConversions redisCustomConversions() {
            return new RedisCustomConversions(
                    Arrays.asList(new OffsetDateTimeToBytesConverter(), new BytesToOffsetDateTimeConverter(),new BytesToDateConverter()));
        }
         
        class CustomRedisTypeMapper extends DefaultRedisTypeMapper {
    
        }
    

提交回复
热议问题