This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Data Couchbase 5.4.0!spring-doc.cn

Caching

This chapter describes additional support for caching and @Cacheable.spring-doc.cn

Configuration & Usage

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.spring-doc.cn

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

To make it work, you need to add the @EnableCaching annotation and configure the cacheManager bean:spring-doc.cn

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();
  }

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).spring-doc.cn

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.spring-doc.cn

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.;
}

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.spring-doc.cn

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