Spring 引导缓存大小

Spring Boot Cachable Cache Size

我想配置我的缓存大小。我正在使用 @EnableCaching。这是我的缓存存储库。

VendorRepository

public interface VendorRepository extends Repository<Vendor, Long> {

@Cacheable("vendorByUsername")
Vendor getVendorByUsername(String username);

@CacheEvict(value = {"vendorByUsername", "vendor", "vendors"}, allEntries = true)
Vendor save(Vendor vendor);

@Cacheable("vendor")
Vendor findOne(Long id);

@Cacheable("vendors")
List<Vendor> findAll();
}

它现在运行良好,但我想设置最大缓存大小。我如何在我的主配置文件中配置它?

@Jaiwo99是正确的

Spring的缓存抽象不处理“管理”缓存内容的特定语义和“低级”细节(例如大小,或类似相关的 eviction/expiration)。这在很大程度上是因为这些低级别的管理细节在不同的缓存提供商之间差异很大。

例如,一些缓存 providers/implementations 是高度分布式的,具有不同的一致性、冗余和控制延迟机制等策略。因此,鉴于某些提供商甚至没有实现所述功能,或者具有非常不同的“一致性”策略等,因此很难在这些功能之上提供一致的抽象。

无论如何,Spring 参考指南中的这一部分可能总结得最好...

8.7. How can I Set the TTL/TTI/Eviction policy/XXX feature?

Directly through your cache provider. The cache abstraction is an abstraction, not a cache implementation. The solution you use might support various data policies and different topologies that other solutions do not support (for example, the JDK ConcurrentHashMap — exposing that in the cache abstraction would be useless because there would no backing support). Such functionality should be controlled directly through the backing cache (when configuring it) or through its native API.

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-specific-config

干杯!

您可以将 Caffeine 实现与 spring-boot-starter-cache 一起使用,并在 application.properties 或 application.yml 文件中设置大小。

spring.cache.caffeine.spec=maximumSize=500

并添加到 pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
        <version>2.5.6</version>
    </dependency>
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
        <version>3.0.4</version>
    </dependency>