gpt4 book ai didi

java - Spring 可缓存注释在部署完成之前不起作用

转载 作者:行者123 更新时间:2023-12-01 09:00:22 25 4
gpt4 key购买 nike

我有以下类和接口(interface)(经过简化以使事情变得清晰)。

@Serivce
class Service1 {

@Cacheable("cacheName")
public Metadata preLoadMetadata() {
// load data from database
}
}

@Service
class Service2 implements Loader {

@Autowired @Lazy
private Service1 service1;

@Overrride
public CacheWrapper getCacheWrapper() {
return new CacheWrapper(() -> service1.preLoadMetadata());
}
}

interface Loader {
CacheWrapper getCacheWrapper();
}

class CacheWrapper {

private Callable callable;

public CacheWrapper(Callable callable) {
this.callable = callable;
}

public getCallable() {
return callable;
}
}

Spring bean 负责在部署时加载缓存。

@Component
class LoadCache {

@Autowired
private List<Loader> allLoaders;

@PostConstruct
public void load() {
allLoaders.getCacheWrapper().getCallable().call();
}
}

preLoadMetadata() 不会将数据保存在缓存中,但它会执行。部署完成后,我再次调用相同的方法 preLoadMetadata(),然后它将数据保存在缓存中。

为什么@Cacheable在部署时不起作用?

如果我手动使用Cacheput方法来填充用@PostConstruct注释的方法内的缓存,我能够成功地做到这一点部署。

我使用 Tomcat 作为服务器。
我在 Spring 缓存抽象后面使用 Couchbase 缓存。

最佳答案

如果您想预加载缓存,我建议您使用 ApplicationListener,它将在您的应用程序启动后执行:

@Component
public class CacheInitializer implements ApplicationListener<ContextRefreshedEvent>{

@Autowired
private List<Loader> allLoaders;

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
allLoaders.getCacheWrapper().getCallable().call();
}
}

关于java - Spring 可缓存注释在部署完成之前不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41721790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com