Redis-如何配置自定义转换 [英] Redis - How to configure custom conversions
问题描述
在spring-data-redis中,我们如何配置自定义转换器,这些转换器可以从Spring引导应用程序或配置中自动接线/注入.
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
.从本文档中,尚不清楚如何配置它们.
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屋!