Files
electricity_bill_calc_service/cache/entity.go
T

48 lines
1.4 KiB
Go

package cache
import (
"fmt"
"strings"
"time"
)
func assembleEntityKey(entityName, id string) string {
var keys = make([]string, 0)
keys = append(keys, strings.ToUpper(entityName), id)
var b strings.Builder
b.WriteString(TAG_ENTITY)
for _, s := range keys {
fmt.Fprintf(&b, ":%s", s)
}
return b.String()
}
// 缓存模型名称明确的,使用ID进行检索的实体内容。
func CacheEntity[T any](instance T, relationNames []string, entityName, id string) error {
entityKey := assembleEntityKey(entityName, id)
err := Cache(entityKey, &instance, 5*time.Minute)
for _, relationName := range relationNames {
CacheRelation(relationName, STORE_TYPE_KEY, entityKey)
}
return err
}
// 从缓存中取出模型名称明确的,使用ID进行检索的实体内容。
func RetreiveEntity[T any](entityName, id string) (*T, error) {
entityKey := assembleEntityKey(entityName, id)
instance, err := Retreive[T](entityKey)
return instance, err
}
// 精确的从缓存中删除指定模型名称、指定ID的实体内容。
func AbolishSpecificEntity(entityName, id string) (bool, error) {
entityKey := assembleEntityKey(entityName, id)
return Delete(entityKey)
}
// 从缓存中删除指定模型名称的所有内容。
func AbolishEntity(entityName string) error {
pattern := fmt.Sprintf("%s:%s:*", TAG_ENTITY, strings.ToUpper(entityName))
return DeleteAll(pattern)
}