1、 注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LocalCache {
String prefix();
}
2、切面
@Aspect
@Component
public class LocalCacheAspect {
@Pointcut("@annotation(service.cache.aspect.LocalCache)")
private void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] params = joinPoint.getArgs();
List<String> paramsString = Arrays.stream(params).map(String::valueOf).collect(Collectors.toList());
Signature signature = joinPoint.getSignature();
MethodSignature msg = (MethodSignature) signature;
Object target = joinPoint.getTarget();
Method method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
LocalCache cache = method.getAnnotation(LocalCache.class);
String key = cache.prefix() + String.join("-", paramsString);
Object result = LocalCacheUtils.get(key);
if (Objects.isNull(result)) {
result = joinPoint.proceed();
if (Objects.nonNull(result)) {
LocalCacheUtils.set(key, result);
}
}
return result;
}
}
5、缓存工具类
public class LocalCacheUtils {
private static final Cache<String, Object> COMMON_CACHE = CacheBuilder.newBuilder()
.initialCapacity(2000)
.maximumSize(20000)
.expireAfterWrite(24, TimeUnit.HOURS)
.build();
public static void set(String key, Object value) {
COMMON_CACHE.put(key, value);
}
public static void remove(String key) {
COMMON_CACHE.invalidate(key);
}
public static Object get(String key) {
return COMMON_CACHE.getIfPresent(key);
}
public static void clean() {
COMMON_CACHE.cleanUp();
}
}
4、注解使用
@LocalCache(prefix = CacheKeyConstant.APP_KEY)