gpt4 book ai didi

java - 为了应用程序安全,我们可以在计划的缓存逐出方法中添加 Spring Boot 可缓存方法吗?

转载 作者:行者123 更新时间:2023-12-02 10:15:26 25 4
gpt4 key购买 nike

我正在尝试实现 Spring boot 可缓存。我想缓存 ws 调用的方法响应。

1)我能够根据请求实现缓存。

 @Cacheable(cacheNames = "mycache", key = "#root.target.cacheKey")
public String myMethod() {
}

2) 我安排每天凌晨 1 点之后进行缓存逐出。

@Scheduled(cron = "${1 AM}")
@CacheEvict(cacheNames = "mycache", key = "#root.target.CACHE_KEY")
public void clearCache() {

LOGGER("Cache eviction:: ");

}

这也工作得很好。我的问题是,在没有从浏览器向 @Cacheable 注释方法发送任何请求的情况下进行驱逐后,我可以在驱逐后调用 @Cacheable 注释方法来确保应用程序安全吗?

@Scheduled(cron = "${1 AM}")
@CacheEvict(cacheNames = "mycache", key = "#root.target.CACHE_KEY")
public void clearCache() {

LOGGER("Cache eviction:: ");
myMethod();
}

This is for application safety .Incase @Cacehable fails to cache response it won't impact the application. I do agree that first request after evict will definitely get inside @Cacheable annotated method and add to cache .But need to make sure that I am following the right approach

有人可以透露一些信息,以便我纠正它

最佳答案

所以,我正在查看来源。

@CacheEvict AspectJ pointcut 定义为

/**
* Matches the execution of any public method in a type with the @{@link CacheEvict}
* annotation, or any subtype of a type with the {@code CacheEvict} annotation.
*/
private pointcut executionOfAnyPublicMethodInAtCacheEvictType() :
execution(public * ((@CacheEvict *)+).*(..)) && within(@CacheEvict *);

然后分组为更通用的组

protected pointcut cacheMethodExecution(Object cachedObject) :
(executionOfAnyPublicMethodInAtCacheableType()
|| executionOfAnyPublicMethodInAtCacheEvictType()
|| ...

使用此切入点的advice是一个around建议,这意味着您可以检查方法调用的输入和输出值,并在需要时继续进行实际通话。

Object around(final Object cachedObject) : cacheMethodExecution(cachedObject) {
MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
Method method = methodSignature.getMethod();

CacheOperationInvoker aspectJInvoker = new CacheOperationInvoker() {
public Object invoke() {
try {
// Call your method implementation
return proceed(cachedObject);
}
catch (Throwable ex) {
throw new ThrowableWrapper(ex);
}
}
};

try {
// Evict cache, in your case
return execute(aspectJInvoker, thisJoinPoint.getTarget(), method, thisJoinPoint.getArgs());
}
catch (CacheOperationInvoker.ThrowableWrapper th) {
AnyThrow.throwUnchecked(th.getOriginal());
return null; // never reached
}
}

如您所见,在通过调用 execute 执行缓存驱逐操作之前,通过 proceed 调用该方法实现。

因此您的“测试”调用没有实际意义。

关于java - 为了应用程序安全,我们可以在计划的缓存逐出方法中添加 Spring Boot 可缓存方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718564/

25 4 0
文章推荐: java - 使用模块时如何修补 package-info.java 文件?
文章推荐: java - 多种类型的过滤器