et-go 20240919重建
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.5 KiB

1 month ago
package cacheSer
import (
"fmt"
"gitea.anxinyun.cn/container/common_models"
"gitea.anxinyun.cn/container/common_models/constant/redisKey"
"gitea.anxinyun.cn/container/common_utils"
"log"
"sync"
"time"
)
var once sync.Once
var cacheWindowMaps sync.Map
type CacheServer struct {
CacheWindowMaps *sync.Map
configHelper *common_utils.ConfigHelper
}
func NewCacheServer(configHelper *common_utils.ConfigHelper) *CacheServer {
once.Do(func() {
cacheWindowMaps = sync.Map{}
})
return &CacheServer{
CacheWindowMaps: &cacheWindowMaps,
configHelper: configHelper,
}
}
func (c *CacheServer) CreatFilterWindow(stationId int, itemName string) common_models.CacheWindow {
//新测点滑窗 size默认1
k := fmt.Sprintf("%d-%s", stationId, itemName)
cacheWindow := common_models.NewCacheWindow(k, 1, 0, common_models.FilterParams{})
Filter, err := c.configHelper.GetFilter(stationId)
if err == nil {
for _, item := range Filter.Items {
if itemName == item.FieldName {
cacheWindow = common_models.NewCacheWindow(k, item.WindowSize, item.MethodId, item.Params)
}
}
}
return cacheWindow
}
func (c *CacheServer) UpdateCacheMap(key string, value common_models.CacheWindow) {
c.CacheWindowMaps.Store(key, value)
err := c.configHelper.SetChainedCacheObjWithExpiration(key, value.ToSaveCache(), time.Hour*6)
if err != nil {
log.Printf("updateCacheMap 异常,err=%s", err.Error())
}
}
// ReadCacheMap
// read map 时 判断时间 超过2分钟 重新读取
func (c *CacheServer) ReadCacheMap(stationId int, itemName string) (common_models.CacheWindow, bool) {
key := fmt.Sprintf("%s:%d:%s", redisKey.CacheWindow, stationId, itemName)
if obj, ok := c.CacheWindowMaps.Load(key); ok {
win, ok2 := obj.(common_models.CacheWindow)
return win, ok2
}
if preWindow, err := c.configHelper.GetCacheWindowObj(key); err == nil {
//过期
if preWindow.CheckExpiration() {
preData := preWindow.DeQueueAll()
reloadWindow := c.CreatFilterWindow(stationId, itemName)
if len(preData) > 0 {
for _, datum := range preData {
reloadWindow.EnQueue(datum)
}
return reloadWindow, true
}
}
return preWindow, true
}
v := c.CreatFilterWindow(stationId, itemName)
return v, true
}
// 获取缓存总数 测试用
func getSizeByCacheWindowMaps() int {
size := 0
cacheWindowMaps.Range(func(key, value any) bool {
size += 1
log.Printf("================ CacheWindowMap-key:%v", key)
return true
})
log.Printf("================= CacheWindowMap-size:%v", size)
return size
}