springboot redis的db动态切换没有作用
springboot2.x以上版本默认采用lettuce,而SpringBoot1.5默认采用的是jedis
//springboot2.x以上版本
LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory(); if (connectionFactory != null) { connectionFactory.setDatabase(切换到指定的db上); /** * 在重置db之后:connectionFactory.setDatabase(i); * 需要将链接刷新:connectionFactory.afterPropertiesSet(); */ connectionFactory.afterPropertiesSet(); this.redisTemplate.setConnectionFactory(connectionFactory); connectionFactory.resetConnection(); }
//springboot1.x
JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(切换到指定的db上);
jedisConnectionFactory.afterPropertiesSet();
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
无法切换的原因:
resetConnnection()方法只会释放Connection对象,RedisClient中的redisUrl对象的属性并未刷新,导致重新生成的Connection对象的DB值仍未改变,随意切换未生效,所以需要调用
connectionFactory.afterPropertiesSet();刷新RedisClient