温馨提示×

springdata redis能连集群吗

小樊
81
2024-11-11 02:14:49
栏目: 云计算

是的,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 操作。你可以根据你的实际需求修改节点配置。

0