我的应用程序在 Spring boot 1.5.1 上
我已经查找了所有与缓存在 Spring Boot 中不起作用相关的常见问题(从同一个类中调用可缓存方法等),但我似乎仍然无法确定我的方法没有缓存的原因。我只是想使用 Spring 内置的简单缓存(即并发 hashmap)。
设置:在 pom.xml 我添加了这个
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
我的配置类如下:
@SpringBootApplication
@Configuration
@EnableCaching
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我有一个 Controller 类,它具有以下获取版本列表的方法。
@RequestMapping(value = "/getVersionList", method = RequestMethod.GET)
public JSONObject getVersionList() {
JSONObject retJSON = new JSONObject();
List<String> versions = fetchVersionService.getVersionList();
retJSON.put("versions", versions);
return retJSON;
}
还有 FetchVersionService 类,我有缓存此版本列表的可缓存方法
@Cacheable("versions")
public List<String> getVersionList() {
System.out.println("If there is something in the cache, it should not hit here.");
return randomService.getVersions(); //another service class that gets versions from a remote location, which takes a long time
}
每当我对这个函数进行多次 GET 调用时,它总是进入函数内部,即使我只希望它执行一次函数。由于某种原因,它没有缓存结果。 有什么想法我的设置出错了吗?非常感谢。
最佳答案
在这个问题下的评论中,@irfanhasan 提到他们导入了错误的包,但没有确定的回应。 我遇到了同样的问题。我尝试使用 @Cachable 注释,但它不起作用。我发现它被导入为:
import springfox.documentation.annotations.Cacheable
代替:
import org.springframework.cache.annotation.Cacheable;
仔细查看您的 IDE 导入。
关于java - Spring Boot - 缓存不起作用,如何正确设置缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54565632/