@@ -59,16 +59,21 @@ func MSet(items map[string]any, ttl time.Duration) { std.MSet(items, ttl) }
5959// CacheNotExist 表示缓存不存在的特殊值,避免缓存穿透
6060var CacheNotExist = "_cache_not_exist_"
6161
62- // MGetOrFind 根据key prefix + keys(eg: ids) 批量获取缓存值,不存在则调用回调函数获取(eg: DB)数据
62+ // MGetOrElse 根据key prefix + keys(eg: ids) 批量获取缓存值,不存在则调用回调函数获取(eg: DB)数据
6363//
6464// 示例:
6565//
6666// ids := []uint{1, 2, 3}
6767// userList := cache.MGetElse("user:", ids, cacheTTL, func(keys []uint) map[uint]*models.User {
6868// return db.ListByIDs(keys)
6969// })
70- func MGetOrFind [K comdef.SimpleType , T any ](keyPrefix string , keys []K , cacheTTL time.Duration , queryFn func (keys []K ) map [K ]T ) []T {
71- return MGetCacheOrFind (std , keyPrefix , keys , cacheTTL , queryFn )
70+ func MGetOrElse [K comdef.SimpleType , T any ](
71+ keyPrefix string ,
72+ keys []K ,
73+ cacheTTL time.Duration ,
74+ queryFn func (keys []K ) (map [K ]T , error ),
75+ ) ([]T , error ) {
76+ return MGetElseUse (std , keyPrefix , keys , cacheTTL , queryFn )
7277}
7378
7479// Keys get the keys of the default cache
@@ -116,10 +121,16 @@ func TypedInCache[T any](c *Cache, key string) (T, bool) {
116121 return res , true
117122}
118123
119- // MGetCacheOrFind 根据key prefix + keys(eg: ids) 批量获取缓存值,不存在则调用回调函数获取(DB)数据
120- func MGetCacheOrFind [K comdef.SimpleType , T any ](c * Cache , prefix string , keys []K , cacheTTL time.Duration , queryFn func (keys []K ) map [K ]T ) []T {
124+ // MGetElseUse 根据key prefix + keys(eg: ids) 批量获取缓存值,不存在则调用回调函数获取(DB)数据
125+ func MGetElseUse [K comdef.SimpleType , T any ](
126+ c * Cache ,
127+ prefix string ,
128+ keys []K ,
129+ cacheTTL time.Duration ,
130+ queryFn func (keys []K ) (map [K ]T , error ),
131+ ) ([]T , error ) {
121132 if len (keys ) == 0 {
122- return make ([]T , 0 )
133+ return make ([]T , 0 ), nil
123134 }
124135
125136 // 构建完整的缓存键list
@@ -158,11 +169,14 @@ func MGetCacheOrFind[K comdef.SimpleType, T any](c *Cache, prefix string, keys [
158169 }
159170 }
160171 if len (missKeys ) == 0 {
161- return dataList
172+ return dataList , nil
162173 }
163174
164175 // 调用回调函数获取缺失的缓存值
165- missDataMap := queryFn (missKeys )
176+ missDataMap , err := queryFn (missKeys )
177+ if err != nil {
178+ return nil , err
179+ }
166180 netSetMap := make (map [string ]any , len (missKeys ))
167181
168182 // 合并结果
@@ -178,7 +192,7 @@ func MGetCacheOrFind[K comdef.SimpleType, T any](c *Cache, prefix string, keys [
178192 }
179193
180194 c .MSet (netSetMap , cacheTTL )
181- return dataList
195+ return dataList , nil
182196}
183197
184198//
0 commit comments