如何将redis CrudRepository与数据库相关联

时间:2017-04-11 03:52:40

标签: redis spring-data spring-data-redis spring-repositories

我在spring-boot 1.4应用程序中使用spring-data-redis。我有两个不同的CrudRepositories。但是,我正在努力将它们与各自的Connection工厂联系起来。

底线是:我希望PersonRedisRepository使用db#6和OtherPurposeRedisRepository来使用db#3。为了最大限度,我不能100%确定我处理此事的方式是否正确。

存储库

interface PersonRedisRepository extends CrudRepository<Person, String> {

}

interface OtherPurposeRedisRepository extends CrudRepository<OtherPurpose, String> {

}

人员存储库的配置

@EnableRedisRepositories(basePackageClasses = [PersonRedisRepository.class], redisTemplateRef = "personRedisTemplate")
class RedisConfigurationForPerson {

@Bean(name = "personFactory")
public RedisConnectionFactory personJedisConnectionFactory() {
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory()
    jedisConnectionFactory.usePool = true
    jedisConnectionFactory.hostName = "127.0.0.1"
    jedisConnectionFactory.database = 6

    return jedisConnectionFactory
}

@Bean(name = "personRedisTemplate")
public RedisTemplate<byte[], byte[]> availabilityCacheRedisTemplate() {
    RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>()
    template.setConnectionFactory(personJedisConnectionFactory())

    template
}
}

其他用途存储库的配置

@EnableRedisRepositories(basePackageClasses = [OtherPurpsoseRepository.class], redisTemplateRef = "otherPurposeRedisTemplate")
class RedisConfigurationForOtherPurpose {

@Bean(name = "otherPurposeFactory")
public RedisConnectionFactory otherPurposeJedisConnectionFactory() {
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory()
    jedisConnectionFactory.usePool = true
    jedisConnectionFactory.hostName = "127.0.0.1"
    jedisConnectionFactory.database = 3

    return jedisConnectionFactory
}

@Bean(name = "otherPurposeRedisTemplate")
public RedisTemplate<byte[], byte[]> otherPurposeRedisTemplate() {
    RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>()
    template.setConnectionFactory(otherPurposeJedisConnectionFactory())

    template
}
}

一切正常,我可以使用两个存储库进行读/写。但是,它们都在db 6上读/写。

1 个答案:

答案 0 :(得分:2)

另一个人和你有同样的问题。即使这些示例是针对jpa存储库的,这些链接也可以帮助您:

Spring Boot Configure and Use Two DataSources

http://www.baeldung.com/spring-data-jpa-multiple-databases

首先将配置数据源与@Primay注释绑定,然后指定您正在处理的数据源。这是第一部分。我很快看了第二部分,后来我会更深入。完成后会更新我的psot;)