工程结构
main.go
package main
import (
"fmt"
"log"
"github.com/zhuge20100104/laonanhai/snowflakedemo/sfnake"
)
func main() {
sID, err := sfnake.SFlake.GetID()
if err != nil {
log.Fatalf("snow flake get id err: %v\n", err)
}
fmt.Printf("Get sid from snow flake: %v\n", sID)
}
sfnake.go
package sfnake
import (
"github.com/sony/sonyflake"
)
var (
SFlake *SnowFlake
)
// SnowFlake SnowFlake算法结构体
type SnowFlake struct {
sFlake *sonyflake.Sonyflake
}
func init() {
SFlake = NewSnowFlake()
}
// 模拟获取本机的机器ID
func getMachineID() (mID uint16, err error) {
mID = 10
return
}
func NewSnowFlake() *SnowFlake {
st := sonyflake.Settings{}
// machineID是个回调函数
st.MachineID = getMachineID
return &SnowFlake{
sFlake: sonyflake.NewSonyflake(st),
}
}
func (s *SnowFlake) GetID() (uint64, error) {
return s.sFlake.NextID()
}
程序输出如下
有疑问加站长微信联系(非本文作者)