Spring redis手動リフレッシュキャッシュ機能
12988 ワード
Spring redis手動リフレッシュキャッシュ機能
背景
バックグラウンド・データベース・キャッシュとしてredisを使用する場合、通常、一定の時間で期限が切れます.ただし、特定の場合(予想外)、バックグラウンドデータは更新され、キャッシュ内のデータは手動で同期する必要があります.
構想
redisキャッシュをリフレッシュする方法を抽出し、コンテナに登録します.必要に応じて登録されたリフレッシュメソッドを呼び出し、redisキャッシュを更新します.
インプリメンテーション
1.注記
注記される方法は、Redisをリフレッシュする方法です.
2.容器
すべてのリフレッシュ・キャッシュを格納する方法:
3.spring beanポストプロセッサ
RefreshCacheで注記されたすべてのメソッドをCacheInvokerコンテナに格納
使用例:
説明@RefreshCache注記は、spring管理のインスタンスでのみ有効であり、クラスに@Component注記があります.
コードウェアハウス
https://gitee.com/thanksm/redis_learn/tree/master/refresh
背景
バックグラウンド・データベース・キャッシュとしてredisを使用する場合、通常、一定の時間で期限が切れます.ただし、特定の場合(予想外)、バックグラウンドデータは更新され、キャッシュ内のデータは手動で同期する必要があります.
構想
redisキャッシュをリフレッシュする方法を抽出し、コンテナに登録します.必要に応じて登録されたリフレッシュメソッドを呼び出し、redisキャッシュを更新します.
インプリメンテーション
1.注記
注記される方法は、Redisをリフレッシュする方法です.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RefreshCache {
String value() default "";
}
2.容器
すべてのリフレッシュ・キャッシュを格納する方法:
@Data
@Slf4j
public class CacheInvoker {
private static List<CacheInvoker> invokers = new ArrayList<>();
private Object targetObj;
private Method targetMethod;
public CacheInvoker(Object targetObj, Method targetMethod) {
this.targetObj = targetObj;
this.targetMethod = targetMethod;
}
public static void addInvoker(CacheInvoker cacheInvoker) {
invokers.add(cacheInvoker);
}
public static void addInvokers(List<CacheInvoker> otherInvokers) {
invokers.addAll(otherInvokers);
}
public void doInvoke() {
Method method = getTargetMethod();
Object target = getTargetObj();
log.info(" :{}", method.toString());
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, target);
}
public static void doInvokes() {
log.info(" {} , ", invokers.size());
invokers.forEach(CacheInvoker::doInvoke);
}
}
3.spring beanポストプロセッサ
RefreshCacheで注記されたすべてのメソッドをCacheInvokerコンテナに格納
@Component
public class RefreshCacheBeanProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> clazz = bean.getClass();
Method[] methods = clazz.getDeclaredMethods();
List<CacheInvoker> invokers = Stream.of(methods)
.filter(method -> method.isAnnotationPresent(RefreshCache.class))
.map(method -> {
CacheInvoker invoker = new CacheInvoker(bean, method);
invoker.doInvoke();
return invoker;
})
.collect(Collectors.toList());
CacheInvoker.addInvokers(invokers);
return bean;
}
}
使用例:
@Slf4j
@Service
public class RedisService {
@RefreshCache
public void initCache() {
log.info(" redis ");
}
}
説明
コードウェアハウス
https://gitee.com/thanksm/redis_learn/tree/master/refresh