Fork me on GitHub

Using the cache


Ninja supports Memcached ( as primary caching layer. In standalone mode Ninja uses EhCache ( 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.

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.

Configuring Memcached

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


// user and password are optional

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

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