Fork me on GitHub

Using the cache

Introduction

Ninja supports Memcached (http://www.danga.com/memcached/) as primary caching layer. In standalone mode Ninja uses EhCache (https://www.ehcache.org/) as default implementation.

In production on multiple machines always use Memcached. On a single machine and when developing your application it is fine to use EhCache. If you are running EhCache on a cluster with multiple machines - your machines will have a state that is not compatible with the way Ninja works.

Using a cache is one of the best ways to improve the performance of your application. But always keep in mind that a cache can fail at any point in time. Design your application accordingly!

Using NinjaCache

Using Ninja's caching facilities is straightforward. You inject NinjaCache into the classes that want to use caching and you are ready to go.

@Inject 
NinjaCache ninjaCache;

public Result allPosts() {

    List<Post> posts = ninjaCache.get("posts", List.class);
    if(posts == null) {
        posts = postDao.findAll();
        ninjaCache.set("posts", posts, "30mn");
    }

    return Results.html().render(posts);

}

NinjaCache provides a range of methods to store, retrieve and manipulate data in your cache.

Some methods have a duplicate “safe” method ( eg. ninjaCache.safeDelete(…) vs. ninjaCache.delete(…)). The difference is that the methods prefixed with “safe” issue a blocking call waiting for the call to be successful, while the unprefixed methods issue a fire-and-forget call that does not guarantee that call succeeds. You should prefer the non-safe methods as they do not block your application.

Duration can optionally be set in days(“2d”), hours (“2h”), minutes (“2mn”) or seconds (“2s”). It defaults to 30 days.

Configuring Memcached

To use Memcached you have to add the following configuration variables to your application.conf file:

cache.implementation=ninja.cache.CacheMemcachedImpl

memcached.host=127.0.0.1:11211

// user and password are optional
memcached.user=USER          
memcached.password=PASSWORD        

When you are using multiple Memcached instances you can specify them via:

memcached.host=127.0.0.1:11211 127.0.0.1:11212 127.0.0.1:11213

As usual you can prefix your variables to use Memcached in production and EhCache while developing and testing:

%prod.cache.implementation=ninja.cache.CacheMemcachedImpl