本文介绍在spring boot下,如何为redis配置多个database数据源。

一、pom依赖
pom.xml文件:spring boot版本使用的是2.6.10版本。

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.10</version><relativePath/> <!-- lookup parent from repository --></parent><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><!--1.x 版本默认采用的连接池技术的Jedis2.0 以上的版本默认连接池是Lettuce如果采用Jedis,需要排除Lettuce的依赖--><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.7.1</version></dependency>

二、配置Redis
1、application.yml配置文件:

##################### Redis配置 ######################redis:# 此处填写你的Redis服务器的实际IP端口号host: 127.0.0.1port: 6379# 此处填写登录Redis的真实密码password: 123456# 连接超时时间,毫秒timeout: 3000jedis:pool:# 最大连接数max-active: 50# 最大连接阻塞等待时间,毫秒max-wait: 1000# 最大空闲连接数max-idle: 20# 最小空闲连接数,默认0min-idle: 5# 在获取连接时是否检查有效性test-on-borrow: true# 在归还连接时是否检查有效性test-on-return: falsedatabase:# 列车信息数据库索引train-db: 4# 用户信息数据库索引user-db: 2

以上配置中,train-db 和 user-db就是两个不同的Redis数据库,我们可以根据需要配置任意个。

database:# 列车信息数据库索引train-db: 4# 用户信息数据库索引user-db: 2

2、配置类:RedisConfig.java

import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.RedisPassword;import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.connection.RedisStandaloneConfiguration;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.StringRedisSerializer;import redis.clients.jedis.JedisPoolConfig;import java.time.Duration;@Configurationpublic class RedisConfig {@Value("${redis.host}")private String hostName;@Value("${redis.port}")private int port;@Value("${redis.password}")private String password;@Value("${redis.database.ilstatus-db}")private int databaseILStatus;@Value("${redis.database.atsstatus-db}")private int databaseATSStatus;@Value("${redis.database.user-db}")private int databaseUser;@Value("${redis.database.train-db}")private int databaseTrain;@Value("${redis.jedis.pool.max-active}")private int maxTotal; //连接池中最大连接数@Value("${redis.jedis.pool.max-idle}")private int maxIdle; //最大空闲连接数@Value("${redis.jedis.pool.min-idle}")private int minIdle; //最小空闲连接数@Value("${redis.jedis.pool.max-wait}")private int maxWait; //当池内没有可用的连接时,最大等待时间@Value("${redis.jedis.pool.test-on-borrow}")private boolean testOnBorrow; //在获取连接时是否检查有效性@Value("${redis.jedis.pool.test-on-return}")private boolean testOnReturn; //在归还连接时是否检查有效性public static final String REDIS_TEMPLATE_USER = "userRedisTemplate";public static final String REDIS_TEMPLATE_TRAIN = "trainRedisTemplate";@Bean(REDIS_TEMPLATE_USER)public RedisTemplate<String, Object> userRedisTemplate() {return getRedisTemplate(databaseUser);}@Bean(REDIS_TEMPLATE_TRAIN)public RedisTemplate<String, Object> trainRedisTemplate() {return getRedisTemplate(databaseTrain);}private RedisTemplate<String, Object> getRedisTemplate(int database) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate();redisTemplate.setConnectionFactory(getRedisConnectionFactory(database));/** key采用StringRedisSerializer序列化 */redisTemplate.setValueSerializer(new StringRedisSerializer());redisTemplate.setKeySerializer(new StringRedisSerializer());/** 设置hash key和value的序列化方式 */redisTemplate.setHashValueSerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}private RedisConnectionFactory getRedisConnectionFactory(int database) {/** 单机配置 + 客户端配置 = jedis连接工厂 */JedisConnectionFactory jedisConnectionFactory =new JedisConnectionFactory(getRedisStandaloneConfig(database), getJedisClientConfig());jedisConnectionFactory.afterPropertiesSet();return jedisConnectionFactory;}private RedisStandaloneConfiguration getRedisStandaloneConfig(int database) {RedisStandaloneConfiguration redisStandaloneConfig = new RedisStandaloneConfiguration();redisStandaloneConfig.setHostName(hostName);redisStandaloneConfig.setPort(port);redisStandaloneConfig.setPassword(RedisPassword.of(password));redisStandaloneConfig.setDatabase(database);return redisStandaloneConfig;}private JedisClientConfiguration getJedisClientConfig() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxTotal(maxTotal); //连接池中最大连接数jedisPoolConfig.setMaxIdle(maxIdle); //最大空闲连接数jedisPoolConfig.setMinIdle(minIdle); //最小空闲连接数//当池内没有可用的连接时,最大等待时间jedisPoolConfig.setMaxWait(Duration.ofMillis(maxWait));//在获取连接时是否检查有效性, 默认falsejedisPoolConfig.setTestOnBorrow(testOnBorrow);//在归还连接时是否检查有效性, 默认falsejedisPoolConfig.setTestOnReturn(testOnReturn);JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpccb =(JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();jpccb.poolConfig(jedisPoolConfig);return jpccb.build();}}

三、使用Redis
UserRedisProxy.java:

@Componentpublic class UserRedisProxy {@Resource(name = RedisConfig.REDIS_TEMPLATE_USER)private RedisTemplate<String, Object> redisTemplate; public Object getUserInfo(String key) {returnredisTemplate.opsForValue().get(key);}}

TrainRedisProxy.java:

@Componentpublic class TrainRedisProxy {@Resource(name = RedisConfig.REDIS_TEMPLATE_TRAIN)private RedisTemplate<String, Object> redisTemplate; public Object getTrainInfo(String key) {returnredisTemplate.opsForValue().get(key);}}