Caching

本章介绍了对缓存和 @Cacheable 的其他支持。

This chapter describes additional support for caching and @Cacheable.

Configuration & Usage

从技术上讲,缓存不属于 spring 数据,而是直接在 spring 核心实现。spring 数据包中的大多数数据库实现无法支持 @Cacheable,因为无法存储任意数据。

Technically, caching is not part of spring-data, but is implemented directly in the spring core. Most database implementations in the spring-data package can’t support @Cacheable, because it is not possible to store arbitrary data.

Couchbase 同时支持二进制和 JSON 数据,因此您可从同一数据库中获取两种数据。

Couchbase supports both binary and JSON data, so you can get both out of the same database.

要使其正常工作,您需要添加 @EnableCaching 注释并配置 cacheManager Bean:

To make it work, you need to add the @EnableCaching annotation and configure the cacheManager bean:

Example 1. AbstractCouchbaseConfiguration for Caching
@Configuration
@EnableCaching
public class Config extends AbstractCouchbaseConfiguration {
    // general methods

  @Bean
  public CouchbaseCacheManager cacheManager(CouchbaseTemplate couchbaseTemplate) throws Exception {
  CouchbaseCacheManager.CouchbaseCacheManagerBuilder builder = CouchbaseCacheManager.CouchbaseCacheManagerBuilder
      .fromConnectionFactory(couchbaseTemplate.getCouchbaseClientFactory());
    builder.withCacheConfiguration("mySpringCache", CouchbaseCacheConfiguration.defaultCacheConfig());
    return builder.build();
  }

然后可在 @Cacheable 注释中使用 persistent 标识符,以识别要使用的缓存管理器(您可以配置多个)。

The persistent identifier can then be used on the @Cacheable annotation to identify the cache manager to use (you can have more than one configured).

设置完成后,您可以使用 @Cacheable 注释注释每个方法,以将其透明地缓存在 couchbase 存储分区中。您还可以自定义生成密钥的方式。

Once it is set up, you can annotate every method with the @Cacheable annotation to transparently cache it in your couchbase bucket. You can also customize how the key is generated.

Example 2. Caching example
@Cacheable(value="persistent", key="'longrunsim-'+#time")
public String simulateLongRun(long time) {
    try {
        Thread.sleep(time);
    } catch(Exception ex) {
        System.out.println("This shouldnt happen...");
    }
    return "I've slept " + time + " miliseconds.;
}

如果多次运行该方法,您会先看到一组操作发生,随后是多个获取操作以及没有睡眠时间(这是对耗时执行的伪造)。您想存储什么都可以,当然,如果是 JSON,您可以通过视图进行访问,并在 Web UI 中查看它。

If you run the method multiple times, you’ll see a set operation happening first, followed by multiple get operations and no sleep time (which fakes the expensive execution). You can store whatever you want, if it is JSON of course you can access it through views and look at it in the Web UI.

请注意,要使用 cache.clear() 或 cache.invalidate(),存储分区必须具有主键。

Note that to use cache.clear() or cache.invalidate(), the bucket must have a primary key.