diff --git a/pkg/jwt/jwt.go b/pkg/jwt/jwt.go index 0678e01..ab64790 100644 --- a/pkg/jwt/jwt.go +++ b/pkg/jwt/jwt.go @@ -16,13 +16,20 @@ var ( // CustomClaims 自定义Claims type CustomClaims struct { - UserID uint `json:"userId"` - Username string `json:"username"` - AuthorityID uint `json:"authorityId"` - BufferTime int64 `json:"bufferTime"` + BaseClaims + BufferTime int64 `json:"bufferTime"` jwt.RegisteredClaims } +// BaseClaims 基础Claims +type BaseClaims struct { + UUID string `json:"uuid"` + ID uint `json:"userId"` + Username string `json:"username"` + NickName string `json:"nickName"` + AuthorityID uint `json:"authorityId"` +} + // JWT JWT工具 type JWT struct { SigningKey []byte @@ -42,12 +49,10 @@ func NewJWT(signingKey, issuer string, expiresAt, bufferTime time.Duration) *JWT } // CreateToken 创建token -func (j *JWT) CreateToken(userID uint, username string, authorityID uint) (string, error) { +func (j *JWT) CreateToken(baseClaims BaseClaims) (string, error) { claims := CustomClaims{ - UserID: userID, - Username: username, - AuthorityID: authorityID, - BufferTime: int64(j.BufferTime / time.Second), + BaseClaims: baseClaims, + BufferTime: int64(j.BufferTime / time.Second), RegisteredClaims: jwt.RegisteredClaims{ Issuer: j.Issuer, ExpiresAt: jwt.NewNumericDate(time.Now().Add(j.ExpiresAt)), @@ -59,6 +64,20 @@ func (j *JWT) CreateToken(userID uint, username string, authorityID uint) (strin return token.SignedString(j.SigningKey) } +// CreateClaims 创建Claims +func (j *JWT) CreateClaims(baseClaims BaseClaims) CustomClaims { + return CustomClaims{ + BaseClaims: baseClaims, + BufferTime: int64(j.BufferTime / time.Second), + RegisteredClaims: jwt.RegisteredClaims{ + Issuer: j.Issuer, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(j.ExpiresAt)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1000)), + IssuedAt: jwt.NewNumericDate(time.Now()), + }, + } +} + // ParseToken 解析token func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) { token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) { @@ -84,5 +103,5 @@ func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) { // NeedRefresh 判断是否需要刷新token func (j *JWT) NeedRefresh(claims *CustomClaims) bool { - return claims.ExpiresAt.Time.Sub(time.Now()) < j.BufferTime + return time.Until(claims.ExpiresAt.Time) < j.BufferTime } diff --git a/pkg/timer/timer.go b/pkg/timer/timer.go index 930344b..2023fc4 100644 --- a/pkg/timer/timer.go +++ b/pkg/timer/timer.go @@ -6,76 +6,212 @@ import ( "github.com/robfig/cron/v3" ) -// Timer 定时任务管理器 -type Timer struct { - cron *cron.Cron - tasks map[string]cron.EntryID - mu sync.RWMutex +type Timer interface { + FindCronList() map[string]*taskManager + AddTaskByFuncWithSecond(cronName string, spec string, fun func(), taskName string, option ...cron.Option) (cron.EntryID, error) + AddTaskByJobWithSeconds(cronName string, spec string, job interface{ Run() }, taskName string, option ...cron.Option) (cron.EntryID, error) + AddTaskByFunc(cronName string, spec string, task func(), taskName string, option ...cron.Option) (cron.EntryID, error) + AddTaskByJob(cronName string, spec string, job interface{ Run() }, taskName string, option ...cron.Option) (cron.EntryID, error) + FindCron(cronName string) (*taskManager, bool) + StartCron(cronName string) + StopCron(cronName string) + FindTask(cronName string, taskName string) (*task, bool) + RemoveTask(cronName string, id int) + RemoveTaskByName(cronName string, taskName string) + Clear(cronName string) + Close() } -// NewTimer 创建定时任务管理器 -func NewTimer() *Timer { - return &Timer{ - cron: cron.New(cron.WithSeconds()), - tasks: make(map[string]cron.EntryID), +type task struct { + EntryID cron.EntryID + Spec string + TaskName string +} + +type taskManager struct { + corn *cron.Cron + tasks map[cron.EntryID]*task +} + +type timer struct { + cronList map[string]*taskManager + sync.Mutex +} + +// AddTaskByFunc 通过函数的方法添加任务 +func (t *timer) AddTaskByFunc(cronName string, spec string, fun func(), taskName string, option ...cron.Option) (cron.EntryID, error) { + t.Lock() + defer t.Unlock() + if _, ok := t.cronList[cronName]; !ok { + tasks := make(map[cron.EntryID]*task) + t.cronList[cronName] = &taskManager{ + corn: cron.New(option...), + tasks: tasks, + } + } + id, err := t.cronList[cronName].corn.AddFunc(spec, fun) + t.cronList[cronName].corn.Start() + t.cronList[cronName].tasks[id] = &task{ + EntryID: id, + Spec: spec, + TaskName: taskName, + } + return id, err +} + +// AddTaskByFuncWithSecond 通过函数的方法使用WithSeconds添加任务 +func (t *timer) AddTaskByFuncWithSecond(cronName string, spec string, fun func(), taskName string, option ...cron.Option) (cron.EntryID, error) { + t.Lock() + defer t.Unlock() + option = append(option, cron.WithSeconds()) + if _, ok := t.cronList[cronName]; !ok { + tasks := make(map[cron.EntryID]*task) + t.cronList[cronName] = &taskManager{ + corn: cron.New(option...), + tasks: tasks, + } + } + id, err := t.cronList[cronName].corn.AddFunc(spec, fun) + t.cronList[cronName].corn.Start() + t.cronList[cronName].tasks[id] = &task{ + EntryID: id, + Spec: spec, + TaskName: taskName, + } + return id, err +} + +// AddTaskByJob 通过接口的方法添加任务 +func (t *timer) AddTaskByJob(cronName string, spec string, job interface{ Run() }, taskName string, option ...cron.Option) (cron.EntryID, error) { + t.Lock() + defer t.Unlock() + if _, ok := t.cronList[cronName]; !ok { + tasks := make(map[cron.EntryID]*task) + t.cronList[cronName] = &taskManager{ + corn: cron.New(option...), + tasks: tasks, + } + } + id, err := t.cronList[cronName].corn.AddJob(spec, job) + t.cronList[cronName].corn.Start() + t.cronList[cronName].tasks[id] = &task{ + EntryID: id, + Spec: spec, + TaskName: taskName, + } + return id, err +} + +// AddTaskByJobWithSeconds 通过接口的方法添加任务 +func (t *timer) AddTaskByJobWithSeconds(cronName string, spec string, job interface{ Run() }, taskName string, option ...cron.Option) (cron.EntryID, error) { + t.Lock() + defer t.Unlock() + option = append(option, cron.WithSeconds()) + if _, ok := t.cronList[cronName]; !ok { + tasks := make(map[cron.EntryID]*task) + t.cronList[cronName] = &taskManager{ + corn: cron.New(option...), + tasks: tasks, + } + } + id, err := t.cronList[cronName].corn.AddJob(spec, job) + t.cronList[cronName].corn.Start() + t.cronList[cronName].tasks[id] = &task{ + EntryID: id, + Spec: spec, + TaskName: taskName, + } + return id, err +} + +// FindCron 获取对应cronName的cron +func (t *timer) FindCron(cronName string) (*taskManager, bool) { + t.Lock() + defer t.Unlock() + v, ok := t.cronList[cronName] + return v, ok +} + +// FindTask 获取对应cronName下的task +func (t *timer) FindTask(cronName string, taskName string) (*task, bool) { + t.Lock() + defer t.Unlock() + v, ok := t.cronList[cronName] + if !ok { + return nil, ok + } + for _, t2 := range v.tasks { + if t2.TaskName == taskName { + return t2, true + } + } + return nil, false +} + +// FindCronList 获取所有的任务列表 +func (t *timer) FindCronList() map[string]*taskManager { + t.Lock() + defer t.Unlock() + return t.cronList +} + +// StartCron 开始任务 +func (t *timer) StartCron(cronName string) { + t.Lock() + defer t.Unlock() + if v, ok := t.cronList[cronName]; ok { + v.corn.Start() } } -// Start 启动定时任务 -func (t *Timer) Start() { - t.cron.Start() -} - -// Stop 停止定时任务 -func (t *Timer) Stop() { - t.cron.Stop() -} - -// AddTask 添加定时任务 -func (t *Timer) AddTask(name, spec string, cmd func()) error { - t.mu.Lock() - defer t.mu.Unlock() - - // 如果任务已存在,先删除 - if id, ok := t.tasks[name]; ok { - t.cron.Remove(id) - } - - id, err := t.cron.AddFunc(spec, cmd) - if err != nil { - return err - } - t.tasks[name] = id - return nil -} - -// RemoveTask 删除定时任务 -func (t *Timer) RemoveTask(name string) { - t.mu.Lock() - defer t.mu.Unlock() - - if id, ok := t.tasks[name]; ok { - t.cron.Remove(id) - delete(t.tasks, name) +// StopCron 停止任务 +func (t *timer) StopCron(cronName string) { + t.Lock() + defer t.Unlock() + if v, ok := t.cronList[cronName]; ok { + v.corn.Stop() } } -// HasTask 检查任务是否存在 -func (t *Timer) HasTask(name string) bool { - t.mu.RLock() - defer t.mu.RUnlock() - _, ok := t.tasks[name] - return ok -} - -// ListTasks 列出所有任务 -func (t *Timer) ListTasks() []string { - t.mu.RLock() - defer t.mu.RUnlock() - - names := make([]string, 0, len(t.tasks)) - for name := range t.tasks { - names = append(names, name) +// RemoveTask 从cronName删除指定任务 +func (t *timer) RemoveTask(cronName string, id int) { + t.Lock() + defer t.Unlock() + if v, ok := t.cronList[cronName]; ok { + v.corn.Remove(cron.EntryID(id)) + delete(v.tasks, cron.EntryID(id)) } - return names +} + +// RemoveTaskByName 从cronName使用taskName删除指定任务 +func (t *timer) RemoveTaskByName(cronName string, taskName string) { + fTask, ok := t.FindTask(cronName, taskName) + if !ok { + return + } + t.RemoveTask(cronName, int(fTask.EntryID)) +} + +// Clear 清除任务 +func (t *timer) Clear(cronName string) { + t.Lock() + defer t.Unlock() + if v, ok := t.cronList[cronName]; ok { + v.corn.Stop() + delete(t.cronList, cronName) + } +} + +// Close 释放资源 +func (t *timer) Close() { + t.Lock() + defer t.Unlock() + for _, v := range t.cronList { + v.corn.Stop() + } +} + +// NewTimerTask 创建定时任务管理器 +func NewTimerTask() Timer { + return &timer{cronList: make(map[string]*taskManager)} }