1. 添加Redis依赖
首先,打开您的Spring Boot 项目的 pom.xml 文件并添加以下 Redis 相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2. 配置多个 Redis 连接
接下来在 application.properties 文件中添加 Redis 连接的配置。
假设我们要添加两个 Redis 连接:分别为 Redis1 和 Redis2 添加了配置。
# Redis1 Configuration
spring.redis1.host=localhost
spring.redis1.port=6379
spring.redis1.password=
spring.redis1.pool.max-active=8
spring.redis1.pool.max-wait=-1
spring.redis1.pool.max-idle=8
spring.redis1.pool.min-idle=0
# Redis2 Configuration
spring.redis2.host=localhost
spring.redis2.port=6380
spring.redis2.password=
spring.redis2.pool.max-active=8
spring.redis2.pool.max-wait=-1
spring.redis2.pool.max-idle=8
spring.redis2.pool.min-idle=0
3. 在代码中使用多个 Redis 连接
为了在代码中使用多个 Redis 连接,我们首先需要创建一个配置类 RedisConfiguration
在该类中进行多个 Redis 连接的配置。
注意,这里的 @Primary 注解用于指定默认的 Redis 连接。
@Configuration
public class RedisConfiguration {
@Bean(name = "redis1Template")
@Primary
public RedisTemplate<String, String> redis1Template() {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(redis1ConnectionFactory());
return template;
}
@Bean(name = "redis2Template")
public RedisTemplate<String, String> redis2Template() {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(redis2ConnectionFactory());
return template;
}
@Bean
@Primary
public RedisConnectionFactory redis1ConnectionFactory() {
return new JedisConnectionFactory(new RedisStandaloneConfiguration("localhost", 6379));
}
@Bean
public RedisConnectionFactory redis2ConnectionFactory() {
return new JedisConnectionFactory(new RedisStandaloneConfiguration("localhost", 6380));
}
}
在上述代码中,我们为每个 Redis 连接定义了一个 Redistemplate
并创建了两个 RedisConnectionFactory 类。
接下来,在我们的代码中我们可以使用这些对象来访问不同的 Redis 实例。示例如下:
@Autowired
@Qualifier("redis1Template")
RedisTemplate<String, String> redis1Template;
@Autowired
@Qualifier("redis2Template")
RedisTemplate<String, String> redis2Template;
redis1Template.opsForValue().set("key1", "value1");
String value1 = redis1Template.opsForValue().get("key1");
redis2Template.opsForValue().set("key2", "value2");
String value2 = redis2Template.opsForValue().get("key2");
上述代码在注入时指定了不同的 Qualifier,以便区分两个不同的 Redis 实例。
更多学习资讯,学习源码,请在公众号耶宇星球领取