首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Boot缓存功能不需要spring-boot-starter cache

Spring Boot缓存功能不需要spring-boot-starter cache
EN

Stack Overflow用户
提问于 2021-07-18 21:28:31
回答 1查看 785关注 0票数 1

当您试图使用@Cacheable使用spring引导缓存特性时,您不需要启动模块spring-boot-starter-cache,它在Spring中称为"Spring抽象“。

代码语言:javascript
复制
// 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'
}
代码语言:javascript
复制
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());
}

这就是结果。

代码语言:javascript
复制
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提供如下内容:

代码语言:javascript
复制
org.springframework » spring-context-support
org.springframework.boot » spring-boot-starter

我们已经有spring-boot-starter了,所以深入spring-context-support

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-19 06:41:29

它“工作”,但只对没有缓存或使用地图。spring-context依赖项中唯一可用的支持是NoOpCacheManagerSimpleCacheManager (使用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或咖啡因支持。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68433218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档