Tuesday, April 10, 2012

Spring Cache + Couchbase NoSQL DB

This post expands on the previous Library example using Couchbase as NoSQL database. You can download and configure Couchbase server from their site. Spring Cache is only a cache abstraction so we must implement the backing cache (where the data is stored to and read from), in this case Couchbase.
  1. Implement Cache Manager.  Our cache manager will extend AbstractCacheManager from Spring, which takes care of the boiler-plate code. We will implement only loadCaches method which will be used to preload all caches. When you configure Couchbase using the admin console, one of your configurations is setting up Data Buckets; these buckets will be your caches.

    • We store an array list of cacheNames (data bucket names). This list will be injected by Spring from spring-context file.
    • loadCaches method creates an instance of each Cache. My Couchbase server is configured with 2 buckets, 'default' and 'books' so I will configure 2 Caches (one for each bucket). Default cache will load objects into 'default' data bucket and Books cache will load objects into 'books' bucket. Note: Unlike some other cache servers, Couchbase will not create a new bucket programmatically. All buckets must be configured on the server before your code can use them.
  2. Implement Cache. Our cache class will extend Cache from Spring. Here we connect to the Couchbase server, implement put, get, evict and clear methods.

    • init() establishes a connection to Couchbase server for a specific Bucket name. That bucket name must match your Couchbase configuration.
    • get and put methods are straightforward. Note: Couchbase accepts String objects as keys not allowing spaces.
    • We wrap our cached object in ValueWrapper
  3. Adding Caching with Annotations. Since Couchbase does not like spaces in its keys, for this example we will cache by ISBN (key="#isbn"). Cache (bucket) name is 'books'  (value="books").
  4. Configuring Application Context. Now we will modify our Spring application context file to configure the custom CacheManager and Cache.
    • Use cacheManager as the bean name, that's what Spring Cache looks for. While initializing CacheManager we are passing 2 bucket names configured on Couchbase server.
  5. Maven dependencies.

This is pretty much all you need to plug in Spring Cache with Couchbase.

When you run your JUnit tests you will notice that when you call LibraryService.getBook method the first time, Spring creates a proxy class of your Library Service and will call getBook method on the proxy class. Proxy will call get() to check if the object has been cached. Since this is your first call, the object returned is null and the proxy class will invoke your LibraryService.getBook method. The returned value will then be placed into cache with put(). Second call to the same method (with same parameters) will return the object from cache.