minjay26
敬畏每一行代码

当你save保存的时候你会发现出现StackOverflow Exception,很明显出现了无限循环,可是仅仅是一个save操作,哪里来的无限循环呢?

最终发现就是DateTime导致的,因为将对象映射存为Hash会将对象上的每一个属性存为hashkey,而且属性要是基本类型,,看图就知道问题咋来的了,Datetime上的属性是无限嵌套的.

 

怎么解决?

   

 @WritingConverter
    public static class DateTimeToStringConvert implements Converter<DateTime, Map<String, String>> {
        @Override
        public Map<String, String> convert(DateTime source) {
            Map<String, String> data = new HashMap<>();
            data.put("value", source.toString());
            return data;
        }
    }

    @ReadingConverter
    public static class StringToDateTimeConvert implements Converter<Map<String, Object>, DateTime> {
        @Override
        public DateTime convert(Map<String, Object> source) {
            if (source.containsKey("value")) {
                String dateStr = new String((byte[]) source.get("value"));
                return DateTime.parse(dateStr);
            }
            return null;
        }
    }

需要自定义write与read的转换器,然后你需要将该注册器注入到spring data和spring data redis的convert中去

 @Configuration
    static class RedisConvertConfig{

        @Autowired
        public MappingRedisConverter mappingRedisConverter;

        @PostConstruct
        public void initialConverter() {
            ConversionService conversionService = mappingRedisConverter.getConversionService();
            mappingRedisConverter.setCustomConversions(customConversions());
            if (conversionService instanceof GenericConversionService) {
                ((GenericConversionService) conversionService).addConverter(new DateTimeStringConvert.DateTimeToStringConvert());
                ((GenericConversionService) conversionService).addConverter(new DateTimeStringConvert.StringToDateTimeConvert());
            }
        }

        public CustomConversions customConversions() {
            List<Converter<?, ?>> converterList = new ArrayList<>();
            converterList.add(new DateTimeStringConvert.DateTimeToStringConvert());
            converterList.add(new DateTimeStringConvert.StringToDateTimeConvert());
            return new CustomConversions(converterList);
        }
    }

 

posted on 2017-12-28 11:58  minjay26  阅读(669)  评论(0编辑  收藏  举报