common
公共组件
基础设施层异常处理与工具类
统一异常处理 + 两级缓存 + 工具类通过公共组件封装通用逻辑,让业务代码更简洁
异常处理与工具类
统一异常处理 + 两级缓存 + 工具类通过公共组件封装通用逻辑,让业务代码更简洁
在业务开发中,有大量通用的功能:异常处理、JSON 序列化、缓存管理、工具方法等。如何设计一套公共组件,让业务代码更简洁、更易维护?
业务异常 - 统一的异常类型
public class BizException extends RuntimeException {
private String code;
private String message;
public BizException(String message) {
super(message);
this.code = "BIZ_ERROR";
this.message = message;
}
public BizException(String code, String message) {
super(message);
this.code = code;
this.message = message;
}
// 静态工厂方法
public static BizException of(String message) {
return new BizException(message);
}
}两级缓存 - 本地缓存 + Redis 分布式清除
public class RedisLocalCacheClear<T> implements ILocalCacheClear<T> {
private ILocalCache<T> localCache;
private String topic;
private Function<String, T> loader;
public RedisLocalCacheClear(ILocalCache<T> localCache,
String topic,
Function<String, T> loader) {
this.localCache = localCache;
this.topic = topic;
this.loader = loader;
// 订阅 Redis 清除消息
subscribeInvalidation();
}
@Override
public T get(String key) {
// 先查本地缓存
T value = localCache.get(key);
if (value != null) {
return value;
}
// 本地缓存未命中,加载数据
value = loader.apply(key);
localCache.put(key, value);
return value;
}
@Override
public void invalidate(String key) {
// 清除本地缓存
localCache.remove(key);
// 发布 Redis 消息,通知其他节点清除
publishInvalidation(key);
}
}