feat: 新增 snowid(雪花ID+GORM钩子模板,吸收go-hua); wsc新增SessionClient会话层(吸收两端internal/cloud); jwtx重写为标准三段式HS256+密钥显式传参
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
# snowid
|
||||
|
||||
基于 `bwmarrin/snowflake` 的雪花 ID 生成器(进程内单例)+ GORM 模型 ID 钩子模板。
|
||||
|
||||
## 用法
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/zogo/snowid"
|
||||
|
||||
func main() {
|
||||
if err := snowid.Init(1); err != nil { ... } // 节点ID 0-1023
|
||||
id := snowid.Generate() // int64
|
||||
s := snowid.GenerateString() // string
|
||||
}
|
||||
|
||||
// 生成模型(gorm.io/gen):让 bigint 主键自动填充
|
||||
// gen-model 脚本里:
|
||||
opts = append(opts, gen.WithMethod(snowid.IDMethod{}))
|
||||
// 生成的模型自带 BeforeCreate:Id==0 时填 snowid.Generate()
|
||||
```
|
||||
|
||||
## 注意
|
||||
|
||||
- **必须先 Init 再 Generate**,否则 panic(启动期暴露,不留隐患)。
|
||||
- `InitWithStartTime` 会改全局 Epoch,须在进程首个 NewNode 前调用;同一部署里
|
||||
各服务的 Epoch 口径要一致,ID 才可排序比较。
|
||||
- 多实例部署时节点 ID 不得重复,否则会生成重复 ID。
|
||||
@@ -0,0 +1,69 @@
|
||||
// Package snowid 基于雪花算法的全局唯一 ID 生成器(进程内单例,需先 Init)。
|
||||
//
|
||||
// 运行时:main 里 Init 后调用 Generate/GenerateString。
|
||||
// GORM 模型:IDMethod 交给 gorm.io/gen 的 WithMethod 注入,
|
||||
// 生成的模型自带 BeforeCreate 钩子(Id 为 0 时自动填充 Generate())。
|
||||
package snowid
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/bwmarrin/snowflake"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
node *snowflake.Node
|
||||
once sync.Once
|
||||
initErr error
|
||||
)
|
||||
|
||||
// Init 初始化雪花ID生成器
|
||||
// nodeID: 节点ID,范围 0-1023
|
||||
func Init(nodeID int64) error {
|
||||
once.Do(func() {
|
||||
node, initErr = snowflake.NewNode(nodeID)
|
||||
})
|
||||
return initErr
|
||||
}
|
||||
|
||||
// InitWithStartTime 使用自定义起始时间初始化雪花ID生成器
|
||||
// nodeID: 节点ID,范围 0-1023
|
||||
// startTime: 自定义起始时间(Unix毫秒时间戳)
|
||||
func InitWithStartTime(nodeID int64, startTime int64) error {
|
||||
once.Do(func() {
|
||||
snowflake.Epoch = startTime
|
||||
node, initErr = snowflake.NewNode(nodeID)
|
||||
})
|
||||
return initErr
|
||||
}
|
||||
|
||||
// Generate 生成一个新的雪花ID
|
||||
func Generate() int64 {
|
||||
if node == nil {
|
||||
panic("snowid: not initialized, please call Init() first")
|
||||
}
|
||||
return node.Generate().Int64()
|
||||
}
|
||||
|
||||
// GenerateString 生成字符串形式的雪花ID
|
||||
func GenerateString() string {
|
||||
if node == nil {
|
||||
panic("snowid: not initialized, please call Init() first")
|
||||
}
|
||||
return node.Generate().String()
|
||||
}
|
||||
|
||||
// IDMethod GORM 模型方法模板:交给 gen.WithMethod 注入后,
|
||||
// 生成的模型在 Create 前自动生成雪花ID主键(字段名须为 Id)。
|
||||
type IDMethod struct {
|
||||
Id int64
|
||||
}
|
||||
|
||||
// BeforeCreate 创建前钩子,自动生成雪花ID
|
||||
func (m *IDMethod) BeforeCreate(tx *gorm.DB) error {
|
||||
if m.Id == 0 {
|
||||
m.Id = Generate()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user