go-redis icon indicating copy to clipboard operation
go-redis copied to clipboard

Add ability to create cluster

Open mindscratch opened this issue 9 years ago • 1 comments

The redis-trib.rb program makes it fairly easy to create a redis cluster. Once you have your nodes running you can issue a command like redis-cluster create --replicas 1 $host0:$port $host1:$port $host2:$port $host3:$port $host4:$port $host5:$port

It looks like there's a bunch of stuff that redis-trib does such as allocating slots, updating config, "meeting" nodes, etc. I'd rather not re-implement all of that using go-redis, the other option is to exec the command. It would be greate if go-redis had this "built-in".

mindscratch avatar Dec 07 '15 14:12 mindscratch

package main

import (
    "fmt"
    "github.com/go-redis/redis/v8"
    "log"
)

func main() {
    // Initialize the master node
    masterClient := redis.NewClient(&redis.Options{
        Addr: "localhost:7000", // Change to the desired port
    })

    // Initialize the replica node
    replicaClient := redis.NewClient(&redis.Options{
        Addr: "localhost:7001", // Change to the desired port
    })

    // Enable cluster mode on both nodes
    masterClient.ClusterMeet("localhost", 7001)
    replicaClient.ClusterMeet("localhost", 7000)

    // Assign hash slots
    masterClient.ClusterAddSlotsRange(0, 5460) // Slots 0-5460
    replicaClient.ClusterAddSlotsRange(5461, 10922) // Slots 5461-10922

    // Set replica to follow the master
    replicaClient.ClusterReplicate("node-id-of-master")

    // Print cluster info
    clusterInfo, err := masterClient.ClusterNodes().Result()
    if err != nil {
        log.Fatalf("Error getting cluster info: %v", err)
    }

    fmt.Println(clusterInfo)
}

ljluestc avatar Nov 12 '23 21:11 ljluestc