electricity_bill_calc_service/cache/count.go

59 lines
1.5 KiB
Go

package cache
import (
"fmt"
"strings"
"time"
)
type _CountRecord struct {
Count int64
}
func assembleCountKey(entityName string, additional ...string) string {
var keys = make([]string, 0)
keys = append(keys, strings.ToUpper(entityName))
keys = append(keys, additional...)
var b strings.Builder
b.WriteString(TAG_COUNT)
for _, s := range keys {
fmt.Fprintf(&b, ":%s", s)
}
return b.String()
}
// 向缓存中缓存模型名称明确的包含指定条件的实体记录数量
func CacheCount(relationNames []string, entityName string, count int64, conditions ...string) error {
countKey := assembleCountKey(entityName, conditions...)
cacheInstance := &_CountRecord{Count: count}
err := Cache(countKey, cacheInstance, 5*time.Minute)
for _, relationName := range relationNames {
CacheRelation(relationName, STORE_TYPE_KEY, countKey)
}
return err
}
// 从缓存中获取模型名称明确的,包含指定条件的实体记录数量
func RetreiveCount(entityName string, condtions ...string) (int64, error) {
countKey := assembleCountKey(entityName, condtions...)
exist, err := Exists(countKey)
if err != nil {
return -1, err
}
if !exist {
return -1, nil
}
instance, err := Retreive[_CountRecord](countKey)
if instance != nil && err == nil {
return instance.Count, nil
} else {
return -1, err
}
}
// 删除指定模型名称的数量缓存
func AbolishCountEntity(entityName string) error {
pattern := fmt.Sprintf("%s:%s:*", TAG_COUNT, strings.ToUpper(entityName))
return DeleteAll(pattern)
}