github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xdatabase/xsql/selector.go (about)

     1  package xsql
     2  
     3  import (
     4  	"hash/crc32"
     5  	"math/rand"
     6  	"sync/atomic"
     7  )
     8  
     9  type Selector interface {
    10  	SelectDB(n int) int
    11  }
    12  
    13  type SelectorFunc func(n int) int
    14  
    15  func (fn SelectorFunc) SelectDB(n int) int { return fn(n) }
    16  
    17  func RoundRobinSelector() SelectorFunc {
    18  	var idx int64
    19  	return func(n int) int {
    20  		return int(atomic.AddInt64(&idx, 1)) % n
    21  	}
    22  }
    23  
    24  func ShardSelector(key string) SelectorFunc {
    25  	return func(n int) int {
    26  		return int(crc32.ChecksumIEEE([]byte(key))) % n
    27  	}
    28  }
    29  
    30  func RandomSelector() SelectorFunc {
    31  	return func(n int) int {
    32  		return rand.Intn(n)
    33  	}
    34  }