在Spring Boot中使用RedisTemplate
连接Redis集群,你需要配置Redis的集群节点,并创建RedisTemplate
的Bean实例。以下是一个配置示例:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 在
application.properties
或application.yml
中配置Redis集群节点:
# application.properties
spring.redis.cluster.nodes=node1:6379,node2:6379,node3:6379
或者使用YAML格式:
# application.yml
spring:
redis:
cluster:
nodes:
- node1:6379
- node2:6379
- node3:6379
- 创建配置类来设置
RedisTemplate
:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.List;
@Configuration
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(redisClusterConfiguration());
}
@Bean
public RedisClusterConfiguration redisClusterConfiguration() {
// 假设你已经在配置文件中定义了nodes
// 这里需要读取配置文件中的节点信息
List<String> clusterNodes = ...;
RedisClusterConfiguration config = new RedisClusterConfiguration(clusterNodes);
return config;
}
@Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
return template;
}
}
- 现在你可以在你的服务中注入
RedisTemplate
来使用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
public void setValue(Object key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValue(Object key) {
return redisTemplate.opsForValue().get(key);
}
}