GO实现Redis:GO实现Redis集群(5)

打印 上一主题 下一主题

主题 576|帖子 576|积分 1728


  • 采用一致性hash算法将key分散到不同的节点,客户端可以连接到集群中任意一个节点
  • https://github.com/csgopher/go-redis
  • 本文涉及以下文件:
    consistenthash:实现添加和选择节点方法
    standalone_database:单机database
    client:客户端
    client_pool:实现连接池
    cluster_database:对key进行路由
    com:与其他节点通信
    router,ping,keys,del,select:各类命令的转发具体逻辑
一致性哈希

为什么需要一致性 hash?
在采用分片方式建立分布式缓存时,我们面临的第一个问题是如何决定存储数据的节点。最自然的方式是参考 hash 表的做法,假设集群中存在 n 个节点,我们用 node = hashCode(key) % n 来决定所属的节点。
普通 hash 算法解决了如何选择节点的问题,但在分布式系统中经常出现增加节点或某个节点宕机的情况。若节点数 n 发生变化, 大多数 key 根据 node = hashCode(key) % n 计算出的节点都会改变。这意味着若要在 n 变化后维持系统正常运转,需要将大多数数据在节点间进行重新分布。这个操作会消耗大量的时间和带宽等资源,这在生产环境下是不可接受的。
算法原理
一致性 hash 算法的目的是在节点数量 n 变化时, 使尽可能少的 key 需要进行节点间重新分布。一致性 hash 算法将数据 key 和服务器地址 addr 散列到 2^32 的空间中。
我们将 2^32 个整数首尾相连形成一个环,首先计算服务器地址 addr 的 hash 值放置在环上。然后计算 key 的 hash 值放置在环上,顺时针查找,将数据放在找到的的第一个节点上。
在增加或删除节点时只有该节点附近的数据需要重新分布,从而解决了上述问题。
如果服务器节点较少则比较容易出现数据分布不均匀的问题,一般来说环上的节点越多数据分布越均匀。我们不需要真的增加一台服务器,只需要将实际的服务器节点映射为几个虚拟节点放在环上即可。
参考:https://www.cnblogs.com/Finley/p/14038398.html

lib/consistenthash/consistenthash.go
  1. type HashFunc func(data []byte) uint32
  2. type NodeMap struct {
  3.    hashFunc    HashFunc
  4.    nodeHashs   []int         
  5.    nodehashMap map[int]string
  6. }
  7. func NewNodeMap(fn HashFunc) *NodeMap {
  8.    m := &NodeMap{
  9.       hashFunc:    fn,
  10.       nodehashMap: make(map[int]string),
  11.    }
  12.    if m.hashFunc == nil {
  13.       m.hashFunc = crc32.ChecksumIEEE
  14.    }
  15.    return m
  16. }
  17. func (m *NodeMap) IsEmpty() bool {
  18.    return len(m.nodeHashs) == 0
  19. }
  20. func (m *NodeMap) AddNode(keys ...string) {
  21.    for _, key := range keys {
  22.       if key == "" {
  23.          continue
  24.       }
  25.       hash := int(m.hashFunc([]byte(key)))
  26.       m.nodeHashs = append(m.nodeHashs, hash)
  27.       m.nodehashMap[hash] = key
  28.    }
  29.    sort.Ints(m.nodeHashs)
  30. }
  31. func (m *NodeMap) PickNode(key string) string {
  32.    if m.IsEmpty() {
  33.       return ""
  34.    }
  35.    hash := int(m.hashFunc([]byte(key)))
  36.    
  37.    idx := sort.Search(len(m.nodeHashs), func(i int) bool {
  38.       return m.nodeHashs[i] >= hash
  39.    })
  40.    
  41.    if idx == len(m.nodeHashs) {
  42.       idx = 0
  43.    }
  44.    return m.nodehashMap[m.nodeHashs[idx]]
  45. }
复制代码
HashFunc:hash函数定义,Go的hash函数就是这样定义的
NodeMap:存储所有节点和节点的hash

  • nodeHashs:各个节点的hash值,顺序的
  • nodehashMap
AddNode:添加节点到一致性哈希中
PickNode:选择节点。使用二分查找,如果hash比nodeHashs中最大的hash还要大,idx=0


database/standalone_database.go
  1. type StandaloneDatabase struct {
  2.    dbSet []*DB
  3.    aofHandler *aof.AofHandler
  4. }
  5. func NewStandaloneDatabase() *StandaloneDatabase {
  6.   ......
  7. }
复制代码
把database/database改名为database/standalone_database,再增加一个cluster_database用于对key的路由


resp/client/client.go
[code]// Client is a pipeline mode redis clienttype Client struct {   conn        net.Conn   pendingReqs chan *request // wait to send   waitingReqs chan *request // waiting response   ticker      *time.Ticker   addr        string   working *sync.WaitGroup // its counter presents unfinished requests(pending and waiting)}// request is a message sends to redis servertype request struct {   id        uint64   args      [][]byte   reply     resp.Reply   heartbeat bool   waiting   *wait.Wait   err       error}const (   chanSize = 256   maxWait  = 3 * time.Second)// MakeClient creates a new clientfunc MakeClient(addr string) (*Client, error) {   conn, err := net.Dial("tcp", addr)   if err != nil {      return nil, err   }   return &Client{      addr:        addr,      conn:        conn,      pendingReqs: make(chan *request, chanSize),      waitingReqs: make(chan *request, chanSize),      working:     &sync.WaitGroup{},   }, nil}// Start starts asynchronous goroutinesfunc (client *Client) Start() {   client.ticker = time.NewTicker(10 * time.Second)   go client.handleWrite()   go func() {      err := client.handleRead()      if err != nil {         logger.Error(err)      }   }()   go client.heartbeat()}// Close stops asynchronous goroutines and close connectionfunc (client *Client) Close() {   client.ticker.Stop()   // stop new request   close(client.pendingReqs)   // wait stop process   client.working.Wait()   // clean   _ = client.conn.Close()   close(client.waitingReqs)}func (client *Client) handleConnectionError(err error) error {   err1 := client.conn.Close()   if err1 != nil {      if opErr, ok := err1.(*net.OpError); ok {         if opErr.Err.Error() != "use of closed network connection" {            return err1         }      } else {         return err1      }   }   conn, err1 := net.Dial("tcp", client.addr)   if err1 != nil {      logger.Error(err1)      return err1   }   client.conn = conn   go func() {      _ = client.handleRead()   }()   return nil}func (client *Client) heartbeat() {   for range client.ticker.C {      client.doHeartbeat()   }}func (client *Client) handleWrite() {   for req := range client.pendingReqs {      client.doRequest(req)   }}// Send sends a request to redis serverfunc (client *Client) Send(args [][]byte) resp.Reply {   request := &request{      args:      args,      heartbeat: false,      waiting:   &wait.Wait{},   }   request.waiting.Add(1)   client.working.Add(1)   defer client.working.Done()   client.pendingReqs
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

饭宝

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表