feat: add entgo mixin and sonyflake.

This commit is contained in:
tx7do
2023-05-23 06:37:26 +08:00
parent 184569fee7
commit 1d868f69c2
7 changed files with 160 additions and 153 deletions

50
sonyflake/sonyflake.go Normal file
View File

@@ -0,0 +1,50 @@
package sonyflake
import (
"github.com/sony/sonyflake"
"time"
)
var (
sf *sonyflake.Sonyflake
)
func startTime() time.Time {
return time.Now()
}
func getMachineID() (uint16, error) {
return 0, nil
}
func checkMachineID(uint16) bool {
return false
}
// InitSonyflake 初始化Sonyflake节点单体
func InitSonyflake() {
settings := sonyflake.Settings{
/*StartTime: startTime(),
MachineID: getMachineID,
CheckMachineID: checkMachineID,*/
}
sf = sonyflake.NewSonyflake(settings)
if sf == nil {
panic("sonyflake not created")
}
}
// GenerateSonyflake 生成 Sonyflake ID
func GenerateSonyflake() uint64 {
if sf == nil {
InitSonyflake()
}
if sf == nil {
return 0
}
id, err := sf.NextID()
if err != nil {
return 0
}
return id
}

View File

@@ -0,0 +1,35 @@
package sonyflake
import (
"fmt"
"testing"
"time"
)
func init() {
InitSonyflake()
}
func TestGenerateSonyflake(t *testing.T) {
for i := 0; i < 100; i++ {
id := GenerateSonyflake()
fmt.Println(id)
}
}
func TestGenerateTime(t *testing.T) {
// 秒
fmt.Printf("时间戳(秒):%v;\n", time.Now().Unix())
fmt.Printf("时间戳(纳秒转换为秒):%v;\n", time.Now().UnixNano()/1e9)
// 毫秒
fmt.Printf("时间戳(毫秒):%v;\n", time.Now().UnixMilli())
fmt.Printf("时间戳(纳秒转换为毫秒):%v;\n", time.Now().UnixNano()/1e6)
// 微秒
fmt.Printf("时间戳(微秒):%v;\n", time.Now().UnixMicro())
fmt.Printf("时间戳(纳秒转换为微秒):%v;\n", time.Now().UnixNano()/1e3)
// 纳秒
fmt.Printf("时间戳(纳秒):%v;\n", time.Now().UnixNano())
}