当您试图使用@Cacheable使用spring引导缓存特性时,您不需要启动模块spring-boot-starter-cache,它在Spring中称为"Spring抽象“。
// very basic gradle project setup on spring initializr, with zero dependencies
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}public record Student(String name, int age) {
}
@Repository
public class StudentRepo {
@Cacheable("cache")
public Student get() {
System.out.println("No cache");
return new Student("Fred", 18);
}
}
// in any spring component
@EventListener(ApplicationReadyEvent.class)
public void init() {
System.out.println(repo.get());
System.out.println(repo.get());
System.out.println(repo.get());
System.out.println(repo.get());
System.out.println(repo.get());
}这就是结果。
No cache
Student[name=Fred, age=18]
Student[name=Fred, age=18]
Student[name=Fred, age=18]
Student[name=Fred, age=18]
Student[name=Fred, age=18]显然缓存起作用了。根据文档,它可能是并发的散列图。
我想出了这怎么可能的。按照maven存储库中的依赖项,spring-boot-starter-cache提供如下内容:
org.springframework » spring-context-support
org.springframework.boot » spring-boot-starter我们已经有spring-boot-starter了,所以深入spring-context-support,
org.springframework » spring-beans
org.springframework » spring-context
org.springframework » spring-core他们看起来好眼熟。因为这些正是spring-boot-starter已经拥有的。
从根本上说,初学者模块是传递依赖关系。但即使如此,我还是不明白spring-boot-starter-cache在激活缓存特性方面到底做了什么,因为它只对spring-boot-starter起作用。
现在我想知道的是:为什么要添加spring-boot-starter-cache
发布于 2021-07-19 06:41:29
它“工作”,但只对没有缓存或使用地图。spring-context依赖项中唯一可用的支持是NoOpCacheManager和SimpleCacheManager (使用Map)。
由于对这些实现的支持是EhCache的一部分,所以它不能与适当的缓存(如咖啡因、spring-context-support等)一起工作。对于事务感知缓存也是如此,这也是spring-context-support的一部分。
因此,它“工作”,但并不是真正的,因为它不是一个完整和适当的缓存实现正在使用。
当然,现在也可能有其他的东西吸引spring-context-support来使用它(比如使用available,或者使用Quartz来调度),这使得它可以使用。
在缓存部分中的中也提到了同样的内容。
使用
spring-boot-starter-cache“初学者”快速添加基本的缓存依赖项。启动器引入了spring-context-support。如果手动添加依赖项,则必须包含spring-context-support才能使用JCache、EhCache 2.x或咖啡因支持。
https://stackoverflow.com/questions/68433218
复制相似问题