是的,Spring Data Redis 可以連接到 Redis 集群。為了實現這一點,你需要使用 Spring Data Redis 的 RedisClusterConfiguration
類來配置集群連接。以下是一個簡單的示例,展示了如何配置 Spring Data Redis 以連接到 Redis 集群:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.cluster.RedisClusterConfiguration;
import org.springframework.data.redis.core.cluster.lettuce.LettuceClusterConnectionFactory;
@Configuration
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
// 配置集群節點
RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration();
standaloneConfig.setHostName("node1");
standaloneConfig.setPort(6379);
standaloneConfig.setDatabase(0);
// 配置集群連接工廠
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.commandTimeout(Duration.ofMillis(1000))
.build();
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
clusterConfig.addClusterNode(standaloneConfig);
clusterConfig.addClusterNode(new RedisStandaloneConfiguration().setHostName("node2").setPort(6380).setDatabase(0));
clusterConfig.addClusterNode(new RedisStandaloneConfiguration().setHostName("node3").setPort(6381).setDatabase(0));
LettuceClusterConnectionFactory clusterConnectionFactory = new LettuceClusterConnectionFactory(clusterConfig, clientConfig);
return clusterConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
return template;
}
}
在這個示例中,我們配置了一個包含三個節點的 Redis 集群,并使用 Lettuce 作為客戶端連接工廠。RedisTemplate
用于簡化 Redis 操作。你可以根據你的實際需求修改節點配置。