Redis - 如何配置自定义转换 [英] Redis - How to configure custom conversions

查看:46
本文介绍了Redis - 如何配置自定义转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 spring-data-redis 中,我们如何配置可以从 Spring boot 应用程序或配置中自动连接/注入的自定义转换器.

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

我从 spring 数据 redis 文档中了解了 @ReadingConverter@WritingConverter.从该文档中,不清楚如何配置它们.https://github.com/spring-projects/spring-data-redis/blob/master/src/main/asciidoc/reference/redis-repositories.adoc#redis.repositories.indexes

I read about @ReadingConverter and @WritingConverter from spring data redis documentation. From this documentation, it is not clear on how to configure them. https://github.com/spring-projects/spring-data-redis/blob/master/src/main/asciidoc/reference/redis-repositories.adoc#redis.repositories.indexes

有人知道怎么做吗?

推荐答案

已通过 spring-boot-starter-data-redis:2.0.4.RELEASE 测试.

我遇到了一个问题,即在使用 CrudRepository 时,我的 @RedisHash 实体的 OffsetDateTime 属性没有被存储.

问题是 Jsr310Converters 没有 OffsetDateTime 的转换器.

为了解决这个问题,我创建了一个阅读转换器:

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<byte[], OffsetDateTime> {
    @Override
    public OffsetDateTime convert(final byte[] source) {
        return OffsetDateTime.parse(new String(source), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }
}

和写入转换器:

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

并在配置中注册了一个RedisCustomConversions bean:

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));
    }

}

这篇关于Redis - 如何配置自定义转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆