index.go 2.38 KB
package confbase

import (
	"apigame/util/util-lx/lxalilog"
	"apigame/util/zjson"
	"apigame/util/zredis"
	"fmt"
	"runtime/debug"
)

func SaveCache[T IConfData](gameId string, obj T) {
	info := obj.ConfInfo(gameId)
	_ = zredis.SetEx(zredis.GetConn(), info.CacheKey, zjson.Str(obj), info.CacheTime)
}

func LoadCache[T IConfData](gameId string, obj T) (has bool) {
	has = true
	info := obj.ConfInfo(gameId)
	text, err := zredis.Get(zredis.GetConn(), info.CacheKey)
	if err != nil {
		has = false
		return
	}
	err = zjson.Obj(text, &obj)
	if err != nil {
		fmt.Println(err)
		has = false
		return
	}
	return
}

func LoadData[T1 IConfData, T2 IConfRawData](gameId string, confId any, obj T1) (has bool) {
	confRaw := new(T2)
	info := obj.ConfInfo(gameId)
	db := info.DbMysql
	result := db.Table(info.TableName).Where(fmt.Sprintf("%s = ?", info.KeyName), confId).First(confRaw)

	has = result.RowsAffected != 0
	err := result.Error
	if err != nil {
		lxalilog.Errors(err, "confbase.LoadData error", gameId, confId)
		fmt.Printf("%s", debug.Stack())
		return
	}
	if !has {
		return
	}

	obj.Decode(gameId, confRaw)
	return
}

func FindDuringTime[T1 IConfData, T2 IConfRawData](obj T1, raw *T2, gameId string) (has bool) {
	info := obj.ConfInfo(gameId)
	db := info.DbMysql
	result := db.Table(info.TableName).Where(info.CurrentQuery, info.CurrentArgs...).First(raw)
	has = result.RowsAffected != 0
	return
}

func GetConfig[T1 IConfData, T2 IConfRawData](gameId string, confId any, obj T1) (has bool) {
	has = LoadCache(gameId, obj)
	if has {
		return
	}
	has = LoadData[T1, T2](gameId, confId, obj)
	if !has {
		return
	}
	SaveCache(gameId, obj)
	return
}

// GetCurrent 获取 当前配置
func GetCurrent[T1 IConfData, T2 IConfRawData](gameId string, obj T1) bool {
	has := false
	info := obj.ConfInfo(gameId)
	currentKey := info.CacheCurrent
	currentId := zredis.GetString(zredis.GetConn(), currentKey)
	confRaw := new(T2)
	hasFind := false
	if currentId == "" {
		hasFind = FindDuringTime[T1, T2](obj, confRaw, gameId)
	} else {
		has = GetConfig[T1, T2](gameId, currentId, obj)
		if has {
			if obj.CheckCurrent() {
				hasFind = FindDuringTime[T1, T2](obj, confRaw, gameId)
			}
		} else {
			hasFind = FindDuringTime[T1, T2](obj, confRaw, gameId)
		}
	}
	if hasFind {
		obj.Decode(gameId, confRaw)
		SaveCache(gameId, obj)
		has = true
		currentId = obj.GetUid()
		_ = zredis.Set(zredis.GetConn(), currentKey, currentId)
	}
	return has
}