gitee.com/lh-her-team/common@v1.5.1/shardingbirdsnest/sharding_algorithm.go (about)

     1  // Package shardingbirdsnest sharding algorithm
     2  package shardingbirdsnest
     3  
     4  import (
     5  	bn "gitee.com/lh-her-team/common/birdsnest"
     6  )
     7  
     8  // ChecksumKeyModulo uint32 checksum
     9  func ChecksumKeyModulo(key bn.Key, length int) int {
    10  	// Take the last digit and find the modulus
    11  	return int(key.Key()[key.Len()-1]) % length
    12  }
    13  
    14  // ModuloShardingAlgorithm sharding modulo algorithm
    15  type ModuloShardingAlgorithm struct {
    16  	// Length
    17  	Length int
    18  }
    19  
    20  // NewModuloSA new sharding modulo algorithm
    21  func NewModuloSA(l int) *ModuloShardingAlgorithm {
    22  	return &ModuloShardingAlgorithm{Length: l}
    23  }
    24  
    25  // DoSharding 如果传入 shardingValues 小于 Length 则 最小设置为1
    26  func (a ModuloShardingAlgorithm) DoSharding(shardingValues []bn.Key) [][]bn.Key {
    27  	result := make([][]bn.Key, a.Length)
    28  	// modulo sharding
    29  	for i := range shardingValues {
    30  		modulo := a.DoShardingOnce(shardingValues[i])
    31  		if result[modulo] == nil {
    32  			result[modulo] = []bn.Key{shardingValues[i]}
    33  		} else {
    34  			result[modulo] = append(result[modulo], shardingValues[i])
    35  		}
    36  	}
    37  	return result
    38  }
    39  
    40  // DoShardingOnce do once sharding key
    41  func (a ModuloShardingAlgorithm) DoShardingOnce(key bn.Key) (index int) {
    42  	// last byte modulo
    43  	return ChecksumKeyModulo(key, a.Length)
    44  }