可以在初始化redisTemplate时指定,如
@Bean("redisTemplateDB1") public RedisTemplate<String, String> redisTemplateDB1(@Value("${spring.redis.redis-b.host}") String host, @Value("${spring.redis.redis-b.port}") int port , @Value("${spring.redis.redis-b.database}") int db, @Value("${spring.redis.redis-b.password}") String password) { RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(); redisConfig.setHostName(host); redisConfig.setPassword(password); redisConfig.setPort(port); //指定database redisConfig.setDatabase(db); GenericObjectPoolConfig config=new GenericObjectPoolConfig(); LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder() .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build(); LettuceConnectionFactory lettuceConnectionFactory=new LettuceConnectionFactory(redisConfig, clientConfiguration); RedisTemplate<String, String> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(lettuceConnectionFactory); redisConfig tetemplate; }
也可以在使用前指定,像这样
LettuceConnectionFactory jedisConnectionFactory = (LettuceConnectionFactory) redisTemplate .getConnectionFactory(); //指定db jedisConnectionFactory.setDatabase(1); redisTemplate.setConnectionFactory(jedisConnectionFactory);