58 lines
1.0 KiB
Go
58 lines
1.0 KiB
Go
package mixrepoimpl
|
|
|
|
import (
|
|
"context"
|
|
"github.com/bwmarrin/snowflake"
|
|
"hash/fnv"
|
|
"math"
|
|
"os"
|
|
"voucher/internal/biz/mixrepos"
|
|
"voucher/internal/data"
|
|
)
|
|
|
|
type GenerateRepoImpl struct {
|
|
rdb *data.Rdb
|
|
|
|
node *snowflake.Node
|
|
}
|
|
|
|
func NewGenerateMixRepoImpl(rdb *data.Rdb) (mixrepos.GenerateMixRepo, error) {
|
|
|
|
g := &GenerateRepoImpl{rdb: rdb}
|
|
|
|
name, err := os.Hostname()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
serverId := g.hashMod(name)
|
|
|
|
node, err := snowflake.NewNode(int64(serverId))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
g.node = node
|
|
|
|
return g, nil
|
|
}
|
|
|
|
// hashMod hash mod
|
|
func (s *GenerateRepoImpl) hashMod(hashStr string) int {
|
|
hash := fnv.New32a()
|
|
_, _ = hash.Write([]byte(hashStr))
|
|
|
|
hashValue := hash.Sum32()
|
|
return int(math.Mod(float64(hashValue), 32))
|
|
}
|
|
|
|
// GeneratorString 生成字符串
|
|
func (s *GenerateRepoImpl) GeneratorString(_ context.Context) string {
|
|
return s.node.Generate().String()
|
|
}
|
|
|
|
// GeneratorNumber 生成 int64
|
|
func (s *GenerateRepoImpl) GeneratorNumber(_ context.Context) int64 {
|
|
return s.node.Generate().Int64()
|
|
}
|