init: UserBaseService (backend + deploy + scripts)
ci-userbase-service / build-and-push (push) Successful in 40s
ci-userbase-service / build-and-push (push) Successful in 40s
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package com.yunhai.userbase.utils;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* @author chenx
|
||||
* @date 2026/1/6 20:54
|
||||
* @description 通用缓存封装
|
||||
*/
|
||||
|
||||
public final class CacheKitUtils {
|
||||
private CacheKitUtils() {}
|
||||
|
||||
/**
|
||||
* 泛型模板:先读缓存 → 没有则调用 loader → 回写缓存 → 返回结果
|
||||
*
|
||||
* @param redisUtil 你的 RedisUtil
|
||||
* @param key 缓存键
|
||||
* @param expireSec 过期秒数
|
||||
* @param loader 实际业务加载器
|
||||
* @param <T> 返回值类型
|
||||
* @return 缓存值或加载值
|
||||
*/
|
||||
public static <T> T getOrLoad(RedisUtil redisUtil,
|
||||
String key,
|
||||
int expireSec,
|
||||
Supplier<T> loader) {
|
||||
// 1. 读缓存
|
||||
if (redisUtil.hasKey(key)) {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
T v = (T) redisUtil.get(key);
|
||||
if (v != null) {
|
||||
return v;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 仅打印,继续走 loader
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 加载
|
||||
T value = loader.get();
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 3. 回写缓存
|
||||
try {
|
||||
redisUtil.set(key, value, expireSec);
|
||||
} catch (Exception e) {
|
||||
// 缓存失败不影响主流程
|
||||
e.printStackTrace();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user