refactor: 使用IP端口哈希生成雪花算法节点ID
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -157,16 +158,38 @@ func catchSQLHook() gdb.HookHandler {
|
||||
}
|
||||
}
|
||||
|
||||
func getNodeIdFromIPPort(ctx context.Context) int64 {
|
||||
// 获取本地IP
|
||||
ip, err := utils.GetLocalIP()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
// 获取端口
|
||||
port := g.Cfg().MustGet(ctx, "server.address").String()
|
||||
// 拼接字符串
|
||||
addr := fmt.Sprintf("%s%s", ip, port)
|
||||
|
||||
// 计算哈希(保证唯一且稳定)
|
||||
h := fnv.New64a()
|
||||
h.Write([]byte(addr))
|
||||
hashVal := h.Sum64()
|
||||
|
||||
// 取模 1024 → 得到 0~1023 的合法 node
|
||||
return int64(hashVal % 1024)
|
||||
}
|
||||
|
||||
// ==================== Insert钩子 ====================
|
||||
|
||||
func insertHook(ctx context.Context, in *gdb.HookInsertInput) (result sql.Result, err error) {
|
||||
|
||||
userInfo, err := utils.GetUserInfo(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
node, err := snowflake.NewNode(g.Cfg().MustGet(ctx, "server.workerId").Int64())
|
||||
nodeId := getNodeIdFromIPPort(ctx)
|
||||
if nodeId == 0 {
|
||||
return nil, fmt.Errorf("nodeId cannot be empty")
|
||||
}
|
||||
node, err := snowflake.NewNode(nodeId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -414,7 +437,6 @@ var (
|
||||
|
||||
type Gfdb interface {
|
||||
Exec(ctx context.Context, sql string, args ...any) (sql.Result, error)
|
||||
GetAll(ctx context.Context, sql string, args ...any) (gdb.Result, error)
|
||||
Model(ctx context.Context, tableNameOrStruct ...any) *model
|
||||
Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) error
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user