在服务实现中放置@Cacheable注释的理想位置是什么?



我想缓存数据,但我对@Cacheable注释在我的 spring-boot 项目中的位置有点困惑。

@Override
public Map<String, String> getSampleMethod1() {
Map<String, String> map = getSampleMethod2();
return map;
}
@Override
@Cacheable
public Map<String, String> getSampleMethod2() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String> map1 = getSampleMethod3();
return map1;
}
private Map<String, String> getSampleMethod3(){
Map<String, String> map2 = new HashMap<>();
map2.put("name1", "value1");
map2.put("name2", "value2");
map2.put("name3", "value3");
return map2;
}

上面的代码无法缓存数据。我从控制器调用getSampleMethod1(),每次我点击控制器上的 API 时getSampleMethod2()它都在运行。

任何人都可以帮助我理解缓存中代理对象的概念吗?

只有来自外部类的对getSampleMethod2()的调用才会被截获(实际上是通过代理的调用(。因此,在您的情况下,当您从同一类调用时,您的方法调用不会被拦截,因此@Cacheable将不起作用。

如果希望它工作,您需要创建类的自自动连线对象并调用该对象上的方法。

class MyService{
@Autowired
private ApplicationContext applicationContext;      
MyService self;
@PostConstruct
private void init() {
self = applicationContext.getBean(MyService.class);
}
public Map<String, String> getSampleMethod1() {
Map<String, String> map = self.getSampleMethod2();
return map;
}
}

最新更新