分布式ID生成器

分布式ID生成器

image-20220112080859352

image-20220112081200479

image-20220112081340453

image-20220112081525412

package snowflake

/*
@author RandySun
@create 2022-01-12-8:16
*/
import (
	"fmt"
	"time"

	"github.com/bwmarrin/snowflake"
)

var node *snowflake.Node

func Init(startTime string, machineId int64) (err error) {
	var st time.Time
	st, err = time.Parse("2006-01-02", startTime)
	if err != nil {
		return
	}
	// 毫秒值
	snowflake.Epoch = st.UnixNano() / 1000000
	// 机器id
	node, err = snowflake.NewNode(machineId)
	return
}
func GenId() int64 {
	return node.Generate().Int64()

}

func main() {
	if err := Init("2022-01-12", 1); err != nil {
		fmt.Printf("init failed err:%#v\n", err)
	}

	id := GenId()
	fmt.Println(id)

}

image-20220112083945856

image-20220112082608647

image-20220112082817162

package snowflake

/*
@author RandySun
@create 2022-01-12-8:16
*/
import (
	"fmt"
	"time"

	"github.com/sony/sonyflake"
)

var (
	sonyFlake     *sonyflake.Sonyflake
	sonyMachineId uint16
)

func getMachineId() (uint16, error) {
	return sonyMachineId, nil

}

// 需传入当前的机器ID
func Init1(startTime string, machineId uint16) (err error) {
	sonyMachineId = machineId
	var st time.Time
	st, err = time.Parse("2006-01-02", startTime)
	if err != nil {
		return
	}
	settings := sonyflake.Settings{
		StartTime: st,
		MachineID: getMachineId,
	}
	sonyFlake = sonyflake.NewSonyflake(settings)
	return
}

//GenId 生成id
func GenId1() (id uint64, err error) {
	if sonyFlake == nil {
		err = fmt.Errorf("sony flake not inited")
		return
	}
	id, err = sonyFlake.NextID()
	return id, err

}
func main() {
	if err := Init1("2022-01-12", 1); err != nil {
		fmt.Printf("init failed err:%#v\n", err)
	}

	id, _ := GenId1()
	fmt.Println(id)

}

image-20220112083930016

image-20220112084407101

posted @ 2022-02-13 15:44  RandySun  阅读(111)  评论(0编辑  收藏  举报