electricity_bill_calc_service/cache/search.go

43 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cache
import (
"fmt"
"strings"
"time"
)
func assembleSearchKey(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_SEARCH)
for _, s := range keys {
fmt.Fprintf(&b, ":%s", s)
}
return b.String()
}
// 缓存模型名称明确的使用或者包含非ID检索条件的实体内容。
func CacheSearch[T any](instance T, relationNames []string, entityName string, conditions ...string) error {
searchKey := assembleSearchKey(entityName, conditions...)
err := Cache(searchKey, &instance, 5*time.Minute)
for _, relationName := range relationNames {
CacheRelation(relationName, STORE_TYPE_KEY, searchKey)
}
return err
}
// 从缓存中取得模型名称明确的使用或者包含非ID检索条件的实体内容。
func RetreiveSearch[T any](entityName string, conditions ...string) (*T, error) {
searchKey := assembleSearchKey(entityName, conditions...)
instance, err := Retreive[T](searchKey)
return instance, err
}
// 从缓存中删除全部指定模型名称的实体内容。
func AbolishSearch(entityName string) error {
pattern := fmt.Sprintf("%s:%s:*", TAG_SEARCH, strings.ToUpper(entityName))
return DeleteAll(pattern)
}