是的,Spring Data Redis 可以連接到 Redis 集群。為了實(shí)現(xiàn)這一點(diǎn),你需要使用 Spring Data Redis 的 RedisClusterConfiguration
類來配置集群連接。以下是一個(gè)簡(jiǎn)單的示例,展示了如何配置 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() {
// 配置集群節(jié)點(diǎn)
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;
}
}
在這個(gè)示例中,我們配置了一個(gè)包含三個(gè)節(jié)點(diǎn)的 Redis 集群,并使用 Lettuce 作為客戶端連接工廠。RedisTemplate
用于簡(jiǎn)化 Redis 操作。你可以根據(jù)你的實(shí)際需求修改節(jié)點(diǎn)配置。