The pits encountered when connecting to the redis cluster in the actual project of golang

       The redis in the project directly uses the redis service of aws, redis is a cluster, that is, the pit that golang encounters when connecting to the redis cluster, as follows

       First of all I use redisgo, because it is more convenient to look at the api, it is more like redis-cli, and aws is also recommended. Then the connection was fine at first, I deployed it no less than 10 times, but one day when I deployed it. The server suddenly reported an error when operating redis. "(Error) MOVED xxxx xxx.xxx.xxx.xxx:xxxx", after querying, it was found that redis did not choose to connect to the cluster. I checked again and found that aws officially recommended two redis libraries, redisgo and go-redis Two libraries, redisgo does not support clusters (too bad), and I have deployed so many times without any problems. It may have been connected to the master all the time, and suddenly an error was reported when connected to the slave. Fortunately, it was discovered early.

       When go-redis/redis connects to the database, the official demo gives a bunch of ports.

import "github.com/go-redis/redis/v8"

rdb := redis.NewClusterClient(&redis.ClusterOptions{
    Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},

    // To route commands by latency or randomly, enable one of the following.
    //RouteByLatency: true,
    //RouteRandomly: true,
})

      This can be filled with multiple addresses, as long as you fill in your own address into the slice of string, if there is only one address, fill in only one (the redis cluster in the project may only expose one address to the outside)

clusterClient = redis.NewClusterClient(&redis.ClusterOptions{
	Addrs: []string{"your addr1"},
})

      The redis.NewClusterClient interface is connected to the master by default. If you only want to connect to the slave, you can control it through parameters, and you can check the interface description for details.

      After finally switching the package, the problem of redis cluster connection was successfully solved.

Guess you like

Origin blog.csdn.net/banfushen007/article/details/113175322
Recommended