spring 整合redis 怎么选定指定的数据库

spring 整合redis 怎么选定指定的数据库

2017年03月19日 16:38:11

阅读数:742

前段时间,自学redis时,公司的项目中遇见了一个选定指定库的问题
spring整合redis的配置网上到处都是就不说了,一般都是下面的配置方法

        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="xxx" />
        <property name="port" value="xxx" />
        <property name="password" value="xxx" />
        <property name="poolConfig">
            <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
                <property name="maxIdle" value="100" />
                <property name="maxWaitMillis" value="100000" />
                <property name="maxTotal" value="1000" />
                <property name="testOnBorrow" value="true" />
            </bean>
        </property>
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
 <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
        scope="prototype">
        <property name="connectionFactory" ref="connectionFactory" />
    </bean>
  • 1
  • 2
  • 3
  • 4

可能还有指定默认数据库的配置,但是特殊数据需要保存到非指定的数据库时怎么办?
比如,默认使用的数据库dbindex 为0,有一个数据需要保存到dbindex 为2的数据库(特殊情况);
百度了很久都没有找到解决方案,都是说spring与redis整合的,后来查spring-data-redis的文档,文档上明确说明了支持选择数据库的命令,但是没有知道demo,自己根据api,用下面的代码,实现了选择数据库,代码如下:

RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
        DefaultStringRedisConnection stringRedisConnection = new DefaultStringRedisConnection(redisConnection);
        stringRedisConnection.select(2);
        stringRedisConnection.set("test", "test");
  • 1
  • 2
  • 3
  • 4
  • 5

虽然实现了切换数据库的目的,但是因为刚学习redis,不知道这种写法是否合适,有没有更好的写法,以后知道了,再来更新。

猜你喜欢

转载自blog.csdn.net/f45056231p/article/details/81608558
今日推荐