From 0ddc2f17b9ccb568cee3d345f07de435b32535ec Mon Sep 17 00:00:00 2001 From: qhd <1766646056@qq.com> Date: Sat, 6 Jun 2026 14:34:33 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dsnowflake=E8=8A=82?= =?UTF-8?q?=E7=82=B9=E5=B9=B6=E5=8F=91=E5=88=9D=E5=A7=8B=E5=8C=96=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/gfdb/gfdb.go | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/db/gfdb/gfdb.go b/db/gfdb/gfdb.go index b7f23e6..ecfc50d 100644 --- a/db/gfdb/gfdb.go +++ b/db/gfdb/gfdb.go @@ -7,6 +7,7 @@ import ( "fmt" "regexp" "strings" + "sync" "time" "gitea.com/red-future/common/beans" @@ -29,8 +30,28 @@ import ( var ( localCache *gcache.Cache snowflakeNode *snowflake.Node + snowflakeOnce sync.Once ) +func init() { + ctx := context.Background() + snowflakeOnce.Do(func() { + nodeId := genv.Get("APP_NODE", 1).Int64() + // 安全范围 0~1023 + if nodeId < 0 || nodeId > 1023 { + nodeId = 1 + } + + node, err := snowflake.NewNode(nodeId) + if err != nil { + g.Log().Errorf(ctx, "snowflake init failed: %v", err) + return + } + + snowflakeNode = node + }) +} + // getLocalCache 获取本地缓存实例 func getLocalCache() *gcache.Cache { if localCache == nil { @@ -166,17 +187,8 @@ func insertHook(ctx context.Context, in *gdb.HookInsertInput) (result sql.Result return nil, err } - // 懒加载初始化全局snowflake节点,只创建一次 - if snowflakeNode == nil { - nodeId := genv.Get("APP_NODE", "").Int64() - if g.IsEmpty(nodeId) { - nodeId = 1 - } - node, err := snowflake.NewNode(nodeId) - if err != nil { - return nil, err - } - snowflakeNode = node + if g.IsEmpty(snowflakeNode) { + return nil, fmt.Errorf("snowflakeNode is nil") } for i := range in.Data {