4

Spring Cache与Ehcache 3集成

 2 years ago
source link: https://www.jdon.com/57490
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Spring Cache与Ehcache 3集成

在本文中,我们将研究一些 Spring Cache 概念,然后集成 Ehcache 3。

默认情况下,由于没有额外的提供者,Spring Cache 使用 JCache,它是Spring-Cache-Starter作为依赖项添加时存在于类路径上的默认提供者。它只不过是一个简单的 ConcurrentHashMap。

现在有很多支持的缓存提供程序,我们可以与Spring缓存集成,如Redis、Couchbase、Hazelcast等。今天我们将看看如何集成Ehcache 3。

Spring Cache介绍

@RestController  
public class WebService {  
  
    @Autowired  
    private Service service;  
  
  
   @GetMapping("/{name}")  
    public Person generatePerson(@PathVariable(value = "name") String name) {  
    return service.generatePerson(name);  
}
@org.springframework.stereotype.Service  
public class Service {  
  
    Logger logger = LoggerFactory.getLogger(Service.class);  
  
    @Cacheable(cacheNames = "cacheStore", key = "name")  
    public Person generatePerson(String name) {  
        Person person = new Person(UUID.randomUUID().toString(), name, "Switzerland");  
        logger.info("Generated Person: {}", person);  
        return person;  
    }

方法generatePerson有一个cachable注释定义了一个名为 的缓存cacheStore。通过这种方式,您可以配置将存储键值对的缓存。这里,值是函数的结果,键是输入参数的名称。

要定义您的键,您可以使用 Spring 的表达式语言 ( SpEL ) 格式。如果您不提供键,它将使用输入作为键本身。

将 Ehcache 3 与 Spring Cache 集成 

为了集成Ehcache 3,我们需要添加以下两个依赖。

<dependency>  
   <groupId>org.ehcache</groupId>  
   <artifactId>ehcache</artifactId>  
</dependency>  
  
<dependency>  
   <groupId>javax.cache</groupId>  
   <artifactId>cache-api</artifactId>  
</dependency>

我们不会在这里指定它的版本,因为 spring starter 知道哪个依赖版本是兼容的。

默认情况下,Spring Cache 仅支持 Ehcache 2.x 版本,因此我们必须添加一些配置才能使其与版本 3 兼容。

@Configuration  
public class AppConfig {  
  
    @Bean  
    public CacheManager EhcacheManager() {  
  
        CacheConfiguration<String, Person> cachecConfig = CacheConfigurationBuilder  
          .newCacheConfigurationBuilder(String.class,  
                        Person.class,  
                      ResourcePoolsBuilder.newResourcePoolsBuilder()  
                                .offheap(10, MemoryUnit.MB)  
                                .build())  
.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(10)))  
                .build();  
  
     CachingProvider cachingProvider = Caching.getCachingProvider();  
     CacheManager cacheManager = cachingProvider.getCacheManager();  
       
   javax.cache.configuration.Configuration<String, Person> configuration = Eh107Configuration.fromEhcacheCacheConfiguration(cachecConfig);  
        cacheManager.createCache("cacheStore", configuration);  
        return cacheManager;  
    }  
}

在这里,我们做了一些配置来定义一个cacheStore具有缓存过期和缓存大小等属性的缓存。如果没有来自缓存的键请求,我们将过期时间设置为 10 秒,并且还设置了 10 MB 的堆外大小用于缓存。

代码已上传到GitHub


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK