github.com/hdt3213/godis@v1.2.9/cluster/com.go (about) 1 package cluster 2 3 import ( 4 "errors" 5 "github.com/hdt3213/godis/interface/redis" 6 "github.com/hdt3213/godis/lib/utils" 7 "github.com/hdt3213/godis/redis/client" 8 "github.com/hdt3213/godis/redis/protocol" 9 "strconv" 10 ) 11 12 func (cluster *Cluster) getPeerClient(peer string) (*client.Client, error) { 13 pool, ok := cluster.nodeConnections[peer] 14 if !ok { 15 return nil, errors.New("connection pool not found") 16 } 17 raw, err := pool.Get() 18 if err != nil { 19 return nil, err 20 } 21 conn, ok := raw.(*client.Client) 22 if !ok { 23 return nil, errors.New("connection pool make wrong type") 24 } 25 return conn, nil 26 } 27 28 func (cluster *Cluster) returnPeerClient(peer string, peerClient *client.Client) error { 29 pool, ok := cluster.nodeConnections[peer] 30 if !ok { 31 return errors.New("connection pool not found") 32 } 33 pool.Put(peerClient) 34 return nil 35 } 36 37 var defaultRelayImpl = func(cluster *Cluster, node string, c redis.Connection, cmdLine CmdLine) redis.Reply { 38 if node == cluster.self { 39 // to self db 40 return cluster.db.Exec(c, cmdLine) 41 } 42 peerClient, err := cluster.getPeerClient(node) 43 if err != nil { 44 return protocol.MakeErrReply(err.Error()) 45 } 46 defer func() { 47 _ = cluster.returnPeerClient(node, peerClient) 48 }() 49 peerClient.Send(utils.ToCmdLine("SELECT", strconv.Itoa(c.GetDBIndex()))) 50 return peerClient.Send(cmdLine) 51 } 52 53 // relay function relays command to peer 54 // select db by c.GetDBIndex() 55 // cannot call Prepare, Commit, execRollback of self node 56 func (cluster *Cluster) relay(peer string, c redis.Connection, args [][]byte) redis.Reply { 57 // use a variable to allow injecting stub for testing 58 return cluster.relayImpl(cluster, peer, c, args) 59 } 60 61 // broadcast function broadcasts command to all node in cluster 62 func (cluster *Cluster) broadcast(c redis.Connection, args [][]byte) map[string]redis.Reply { 63 result := make(map[string]redis.Reply) 64 for _, node := range cluster.nodes { 65 reply := cluster.relay(node, c, args) 66 result[node] = reply 67 } 68 return result 69 }