Compare commits

..

11 Commits

Author SHA1 Message Date
ayflying
aa1dc0896d 修复计划任务打断造成协程内上下文执行停止的问题 2025-09-02 12:25:30 +08:00
ayflying
8210ac24db 去掉启动的缓存key 2025-09-02 10:14:01 +08:00
ayflying
cd3de96761 提高kv持久化安全性,按需删除用户缓存 2025-09-01 18:35:43 +08:00
ayflying
ce8ae4d26a 按照执行中的状态进行删除 2025-09-01 18:32:02 +08:00
ayflying
50cfc23ad2 计划任务修改,act与kv使用协程方式执行,不影响其他任务 2025-09-01 18:12:58 +08:00
ayflying
95539038c0 去掉无用配置 2025-08-28 21:43:24 +08:00
ayflying
4b08a9ce84 s3增加方法,允许查看文件的元数据 2025-08-28 18:35:01 +08:00
ayflying
6efdac7bab redis刷新列表,允许打断,防止过长的日志 2025-08-28 18:16:47 +08:00
ayflying
788cb2e6d4 持久化失败会提前结束任务进行抛错 2025-08-27 10:31:48 +08:00
ayflying
dd8c05b344 更新持久化act更新语法 2025-08-27 09:57:45 +08:00
ayflying
e781e132ed 保存计划任务调整 2025-08-22 17:50:37 +08:00
10 changed files with 137 additions and 88 deletions

View File

@@ -5,6 +5,7 @@ import (
v1 "github.com/ayflying/utility_go/api/system/v1"
"github.com/ayflying/utility_go/service"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
@@ -18,10 +19,15 @@ func Boot() (err error) {
//err = service.SystemCron().StartCron()
//用户活动持久化每小时执行一次
service.SystemCron().AddCronV2(v1.CronType_HOUR, func(ctx context.Context) error {
err = service.GameKv().SavesV1()
err = service.GameAct().Saves(ctx)
return err
service.SystemCron().AddCronV2(v1.CronType_HOUR, func(context.Context) error {
go func() {
err = service.GameKv().SavesV1()
err = service.GameAct().Saves()
if err != nil {
g.Log().Error(gctx.New(), err)
}
}()
return nil
}, true)
//初始化自启动方法

View File

@@ -2,6 +2,7 @@ package gameAct
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
@@ -20,7 +21,6 @@ import (
)
var (
ctx = gctx.New()
Name = "game_act"
ActList = gset.New(true)
RunTimeMax *gtime.Time
@@ -46,6 +46,7 @@ func init() {
// @return data *v1.Act: 返回活动信息结构体指针
// @return err error: 返回错误信息
func (s *sGameAct) Info(uid int64, actId int) (data *g.Var, err error) {
var ctx = gctx.New()
if uid == 0 || actId == 0 {
g.Log().Error(ctx, "当前参数为空")
return
@@ -88,6 +89,7 @@ func (s *sGameAct) Info(uid int64, actId int) (data *g.Var, err error) {
// @param data interface{}: 要存储的活动信息数据。
// @return err error: 返回错误信息如果操作成功则返回nil。
func (s *sGameAct) Set(uid int64, actId int, data interface{}) (err error) {
var ctx = gctx.New()
if uid == 0 || actId == 0 {
g.Log().Error(ctx, "当前参数为空")
return
@@ -108,22 +110,20 @@ func (s *sGameAct) Set(uid int64, actId int, data interface{}) (err error) {
return
}
func (s *sGameAct) Saves(ctx context.Context) (err error) {
getCache, _ := pkg.Cache("redis").Get(nil, "cron:game_act")
func (s *sGameAct) Saves() (err error) {
var ctx = gctx.New()
g.Log().Debug(ctx, "开始执行游戏act数据保存了")
//如果没有执行过,设置时间戳
if getCache.Int64() > 0 {
return
} else {
pkg.Cache("redis").Set(nil, "cron:game_act", gtime.Now().Unix(), time.Hour)
}
// 最大允许执行时间
RunTimeMax = gtime.Now().Add(time.Minute * 30)
//遍历执行
ActList.Iterator(func(i interface{}) bool {
//在时间内允许执行
if gtime.Now().Before(RunTimeMax) {
g.Log().Errorf(ctx, "开始执行游戏act数据保存: act%v", i)
g.Log().Debugf(ctx, "开始执行游戏act数据保存:act=%v", i)
err = s.Save(ctx, i.(int))
} else {
g.Log().Errorf(ctx, "游戏act数据保存超时:act=%v", i)
}
return true
})
@@ -133,22 +133,18 @@ func (s *sGameAct) Saves(ctx context.Context) (err error) {
func (s *sGameAct) Save(ctx context.Context, actId int) (err error) {
cacheKey := fmt.Sprintf("act:%v:*", actId)
//获取当前用户的key值
//keys, err := utils.RedisScan(cacheKey)
//if len(keys) > 10000 {
// keys = keys[:10000]
//}
var add = make([]*entity.GameAct, 0)
var update = make([]*entity.GameAct, 0)
//循环获取缓存数据
err = tools.Redis.RedisScanV2(cacheKey, func(keys []string) (err error) {
//判断是否超时
if gtime.Now().After(RunTimeMax) {
g.Log().Debug(ctx, "执行超时了,停止执行!")
g.Log().Debug(ctx, "act执行超时了,停止执行!")
err = errors.New("act执行超时了,停止执行!")
return
}
var add = make([]*entity.GameAct, 0)
var update = make([]*entity.GameAct, 0)
var delKey []string
for _, cacheKey = range keys {
result := strings.Split(cacheKey, ":")
actId, err = strconv.Atoi(result[1])
@@ -156,6 +152,7 @@ func (s *sGameAct) Save(ctx context.Context, actId int) (err error) {
uid = gconv.Int64(result[2])
//uid, err = strconv.ParseInt(result[2], 10, 64)
if err != nil {
g.Log().Error(ctx, err)
continue
}
@@ -184,7 +181,7 @@ func (s *sGameAct) Save(ctx context.Context, actId int) (err error) {
ActId: actId,
}).Fields("uid,act_id").Scan(&data)
if err != nil {
g.Log().Debugf(ctx, "当前数据错误: %v", cacheKey)
g.Log().Errorf(ctx, "当前数据错误: %v", cacheKey)
continue
}
actionData := cacheGet.String()
@@ -201,47 +198,64 @@ func (s *sGameAct) Save(ctx context.Context, actId int) (err error) {
data.Action = actionData
update = append(update, data)
}
//最后删除key
delKey = append(delKey, cacheKey)
}
//批量写入数据库
if len(delKey) > 0 {
updateCount := 0
g.Log().Debugf(ctx, "当前 %v 要更新的数据: %v 条", actId, len(update))
if len(update) > 100 {
for _, v := range update {
v.UpdatedAt = gtime.Now()
_, err2 := g.Model(Name).Where(do.GameAct{
Uid: v.Uid,
ActId: v.ActId,
UpdatedAt: v.UpdatedAt,
updateRes, err2 := g.Model(Name).Where(do.GameAct{
Uid: v.Uid,
ActId: v.ActId,
}).Data(v).Update()
if err2 != nil {
g.Log().Error(ctx, err2)
return
}
if row, _ := updateRes.RowsAffected(); row == 0 {
g.Log().Error(ctx, "本次更新为0更新数据失败: %v", v)
continue
}
//删除缓存
go s.DelCacheKey(ctx, v.ActId, v.Uid)
updateCount++
update = make([]*entity.GameAct, 0)
}
g.Log().Debugf(ctx, "当前 %v 更新数据库: %v 条", actId, updateCount)
update = make([]*entity.GameAct, 0)
var count int64
}
if len(add) > 0 {
dbRes, err2 := g.Model(Name).Batch(50).Data(add).Save()
add = make([]*entity.GameAct, 0)
err = err2
if err != nil {
g.Log().Error(ctx, err2)
return
var count int64
g.Log().Debugf(ctx, "当前 %v 要添加的数据: %v 条", actId, len(add))
if len(add) > 100 {
dbRes, err2 := g.Model(Name).Data(add).Save()
err = err2
if err != nil {
g.Log().Error(ctx, err2)
return
}
count, _ = dbRes.RowsAffected()
if count == 0 {
g.Log().Error(ctx, "当前 %v 写入数据库: %v 条", actId, count)
for _, vTemp := range add {
g.Log().Debugf(ctx, "当前act%vadd写入数据: %v,内容:%v", vTemp.ActId, vTemp.Uid, vTemp.Action)
}
count, _ = dbRes.RowsAffected()
return
}
for _, v := range delKey {
_, err = g.Redis().Del(ctx, v)
if err != nil {
g.Log().Error(ctx, err)
}
for _, v2 := range add {
//删除缓存
go s.DelCacheKey(ctx, v2.ActId, v2.Uid)
}
delKey = make([]string, 0)
g.Log().Debugf(ctx, "当前 %v 写入数据库: %v 条", actId, count)
//g.Log().Debugf(ctx, "当前 %v 写入数据库: %v 条", actId, count)
add = make([]*entity.GameAct, 0)
}
if err != nil {
@@ -254,17 +268,27 @@ func (s *sGameAct) Save(ctx context.Context, actId int) (err error) {
return
}
// 删除缓存key
func (s *sGameAct) DelCacheKey(ctx context.Context, aid int, uid int64) {
cacheKey := fmt.Sprintf("act:%v:%v", aid, uid)
_, err := g.Redis().Del(ctx, cacheKey)
if err != nil {
g.Log().Error(ctx, err)
}
}
// 清空GetRedDot缓存
func (s *sGameAct) RefreshGetRedDotCache(uid int64) {
cacheKey := fmt.Sprintf("gameAct:GetRedDot:%s:%d", gtime.Now().Format("d"), uid)
_, err := pkg.Cache("redis").Remove(gctx.New(), cacheKey)
if err != nil {
g.Log().Error(ctx, err)
g.Log().Error(gctx.New(), err)
g.Dump(err)
}
}
func (s *sGameAct) Del(uid int64, actId int) {
var ctx = gctx.New()
if uid == 0 || actId == 0 {
g.Log().Error(ctx, "当前参数为空")
return

View File

@@ -1,6 +1,8 @@
package gameKv
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
@@ -16,7 +18,6 @@ import (
)
var (
ctx = gctx.New()
Name = "game_kv"
RunTimeMax *gtime.Time
)
@@ -39,37 +40,32 @@ func init() {
// @receiver s: sGameKv的实例。
// @return err: 错误信息如果操作成功则为nil。
func (s *sGameKv) SavesV1() (err error) {
var ctx = gctx.New()
// 最大允许执行时间
RunTimeMax = gtime.Now().Add(time.Minute * 30)
g.Log().Debug(ctx, "开始执行游戏kv数据保存")
getCache, err := pkg.Cache("redis").Get(nil, "cron:game_kv")
//如果没有执行过,设置时间戳
if getCache.Int64() > 0 {
return
} else {
pkg.Cache("redis").Set(nil, "cron:game_kv", gtime.Now().Unix(), time.Hour)
// 定义用于存储用户数据的结构体
type ListData struct {
Uid int64 `json:"uid"`
Kv interface{} `json:"kv"`
}
var list []*ListData
// 初始化列表长度与keys数组一致
list = make([]*ListData, 0)
// 从Redis列表中获取所有用户KV索引的键
//keys, err := utils.RedisScan("user:kv:*")
err = tools.Redis.RedisScanV2("user:kv:*", func(keys []string) (err error) {
//判断是否超时
if gtime.Now().After(RunTimeMax) {
g.Log().Debug(ctx, "执行超时了,停止执行!")
g.Log().Error(ctx, "kv执行超时了,停止执行!")
err = errors.New("kv执行超时了,停止执行!")
return
}
// 定义用于存储用户数据的结构体
type ListData struct {
Uid int64 `json:"uid"`
Kv interface{} `json:"kv"`
}
var list []*ListData
// 初始化列表长度与keys数组一致
list = make([]*ListData, 0)
//需要删除的key
var delKey []string
// 遍历keys获取每个用户的数据并填充到list中
for _, cacheKey := range keys {
//g.Log().Infof(ctx, "保存用户kv数据%v", v)
@@ -102,29 +98,21 @@ func (s *sGameKv) SavesV1() (err error) {
Uid: uid,
Kv: data,
})
delKey = append(delKey, cacheKey)
}
// 将列表数据保存到数据库
if len(list) > 0 {
_, err2 := g.Model("game_kv").Batch(30).Data(list).Save()
list = make([]*ListData, 0)
if len(list) > 100 {
_, err2 := g.Model("game_kv").Data(list).Save()
if err2 != nil {
g.Log().Error(ctx, err2)
return
}
//批量删除key
for _, v := range delKey {
_, err2 = g.Redis().Del(ctx, v)
if err2 != nil {
g.Log().Errorf(ctx, "删除存档失败:%v,err=%v", v, err2)
}
//删除当前key
for _, v := range list {
go s.DelCacheKey(ctx, v.Uid)
}
delKey = make([]string, 0)
list = make([]*ListData, 0)
}
if err != nil {
g.Log().Error(ctx, "当前kv数据入库失败: %v", err)
@@ -135,3 +123,12 @@ func (s *sGameKv) SavesV1() (err error) {
return
}
// 删除缓存key
func (s *sGameKv) DelCacheKey(ctx context.Context, uid int64) {
cacheKey := fmt.Sprintf("user:kv:%v", uid)
_, err := g.Redis().Del(ctx, cacheKey)
if err != nil {
g.Log().Error(ctx, err)
}
}

View File

@@ -60,7 +60,7 @@ type sSystemCron struct {
func New() *sSystemCron {
return &sSystemCron{
taskChan: make(chan func(context.Context) error, 2),
TaskTimeout: time.Minute * 30,
TaskTimeout: time.Minute * 60,
}
}
@@ -333,7 +333,7 @@ func (s *sSystemCron) RunFuncChan() {
//ctx := gctx.New()
func() {
//超时释放资源
ctx, cancel := context.WithTimeout(context.Background(), s.TaskTimeout)
ctx, cancel := context.WithTimeout(gctx.New(), s.TaskTimeout)
defer cancel()
// 使用匿名函数包裹来捕获 panic

View File

@@ -31,7 +31,7 @@ type DataType struct {
Url string `json:"url"` // S3 服务的访问 URL
BucketName string `json:"bucket_name"` // 默认存储桶名称
BucketNameCdn string `json:"bucket_name_cdn"` // CDN 存储桶名称
Provider string `json:"provider"` // S3 服务的提供方
//Provider string `json:"provider"` // S3 服务的提供方
}
// Mod 定义了 S3 模块的结构体,包含一个 S3 客户端实例和配置信息
@@ -184,6 +184,12 @@ func (s *Mod) ListObjects(bucketName string, prefix string) (res <-chan minio.Ob
return
}
// StatObject 获取指定存储桶中指定文件的元数据信息
func (s *Mod) StatObject(bucketName string, objectName string) (res minio.ObjectInfo, err error) {
res, err = s.client.StatObject(ctx, bucketName, objectName, minio.StatObjectOptions{})
return
}
// SetBucketPolicy 设置指定存储桶或对象前缀的访问策略
// 目前使用固定的策略,可根据需求修改
func (s *Mod) SetBucketPolicy(bucketName string, prefix string) (err error) {

View File

@@ -31,8 +31,10 @@ type (
// @param data interface{}: 要存储的活动信息数据。
// @return err error: 返回错误信息如果操作成功则返回nil。
Set(uid int64, actId int, data interface{}) (err error)
Saves(ctx context.Context) (err error)
Saves() (err error)
Save(ctx context.Context, actId int) (err error)
// 删除缓存key
DelCacheKey(ctx context.Context, aid int, uid int64)
// 清空GetRedDot缓存
RefreshGetRedDotCache(uid int64)
Del(uid int64, actId int)

View File

@@ -5,6 +5,10 @@
package service
import (
"context"
)
type (
IGameKv interface {
// SavesV1 方法
@@ -13,6 +17,8 @@ type (
// @receiver s: sGameKv的实例。
// @return err: 错误信息如果操作成功则为nil。
SavesV1() (err error)
// 删除缓存key
DelCacheKey(ctx context.Context, uid int64)
}
)

View File

@@ -38,8 +38,8 @@ type (
// @receiver s: sSystemCron的实例代表一个调度系统。
// @param typ: 任务的类型,决定该任务将被添加到哪个列表中。对应不同的时间间隔。
// @param _func: 要添加的任务函数该函数执行时应该返回一个error。
// @param unique: 是否只在唯一服务器上执行
AddCronV2(typ v1.CronType, _func func(context.Context) error, unique ...bool)
// @param _onlyMain: 是否只在服务器上执行一次,true 唯一执行false 全局执行不判断唯一
AddCronV2(typ v1.CronType, _func func(context.Context) error, _onlyMain ...bool)
// StartCron 开始计划任务执行
//
// @Description:

View File

@@ -48,7 +48,6 @@ func (r *redis) RedisScan(cacheKey string, _key ...string) (keys []string, err e
// redis 批量获取大量数据
func (r *redis) RedisScanV2(cacheKey string, _func func([]string) error, _key ...string) error {
//var keys []string
var err error
@@ -67,9 +66,11 @@ func (r *redis) RedisScanV2(cacheKey string, _func func([]string) error, _key ..
g.Log().Errorf(ctx, "Scan failed: %v", err)
break
}
if len(newKeys) > 0 {
err = _func(newKeys)
if err != nil {
return err
}
}
//这个要放在最后

View File

@@ -1,11 +1,15 @@
package utility_go
import (
"context"
"time"
"github.com/ayflying/utility_go/config"
"github.com/ayflying/utility_go/internal/boot"
_ "github.com/ayflying/utility_go/internal/logic"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gtimer"
)
var (
@@ -14,9 +18,12 @@ var (
)
func init() {
var err error
g.Log().Debug(ctx, "utility_go init启动完成")
// 初始化配置
var err = boot.Boot()
gtimer.SetTimeout(ctx, time.Second*5, func(ctx context.Context) {
err = boot.Boot()
})
if err != nil {
panic(err)