Micronaut Cache

Learn how to use Micronaut's caching annotations.

Authors: Sergio del Amo

Micronaut Version: 1.2.7

1 Getting Started

In this guide, you are going to use Micronaut’s caching annotations to speed up your application.

1.1 What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

1.2 How to complete the guide

We recommend you to follow the instructions in the next sections and create the app step by step. However, you can go right to the completed example.

or

Then, cd into the complete folder which you will find in the root project of the downloaded/cloned project.

2 Writing the Application

Create a Groovy Micronaut app using the Micronaut Command Line Interface.

mn create-app example.micronaut.complete --lang=groovy

The previous command creates a micronaut app with the default package example.micronaut in a folder named complete.

Due to the --lang groovy flag, it generates a Groovy Micronaut app that uses the Gradle build system. However, you could use other build tools such as Maven or other programming languages such as Java or Kotlin.

2.1 Configure the Application

In this sample application, we cache news headlines. Configure your caches in application.yml:

src/main/resources/application.yml
micronaut:
  caches:
    headlines: (1)
      charset: 'UTF-8'
1 Configure a cache called headlines.
By default Micronaut’s cache uses, by default, Caffeine.
Check the properties (maximum-size, expire-after-write and expire-after-access) to configure the size and expiration of your caches. It is important to keep the caches' size under control.

2.2 Micronaut Cache Api

Imagine a service which retrieves headlines for a given month. This operation may be expensive and you may want to cache it.

src/main/groovy/example/micronaut/NewsService.groovy
package example.micronaut

import io.micronaut.cache.annotation.CacheConfig
import io.micronaut.cache.annotation.CacheInvalidate
import io.micronaut.cache.annotation.CachePut
import io.micronaut.cache.annotation.Cacheable

import javax.inject.Singleton
import java.time.Month
import java.util.concurrent.TimeUnit

@Singleton (1)
@CacheConfig("headlines") (2)
class NewsService {

    Map<Month, List<String>> headlines = [
        (Month.NOVEMBER): ["Micronaut Graduates to Trial Level in Thoughtworks technology radar Vol.1",
                "Micronaut AOP: Awesome flexibility without the complexity"],
        (Month.OCTOBER): ["Micronaut AOP: Awesome flexibility without the complexity"]
    ]

    @Cacheable (3)
    List<String> headlines(Month month) {
        TimeUnit.SECONDS.sleep(3) (4)
        headlines[month]
    }

    @CachePut(parameters = ["month"]) (5)
    List<String> addHeadline(Month month, String headline) {
        if (headlines.containsKey(month)) {
            headlines[month] += [headline]
        } else {
            headlines[month] = [headline]
        }
        headlines[month]
    }

    @CacheInvalidate(parameters = ["month"]) (6)
    void removeHeadline(Month month, String headline) {
        if (headlines.containsKey(month)) {
            headlines[month] -= [headline]
        }
    }
}
1 To register a Singleton in Micronaut’s application context annotate your class with javax.inject.Singleton.
2 Specifies the cache name headlines to store cache operation values in.
3 Indicates a method is cacheable. The cache name headlines specified in @CacheConfig is used. Since the method has only one parameter, you don’t need to specify the month parameters attribute of the the annation.
4 Emulate an expensive operation by sleeping for several seconds.
5 The return value is cached with name headlines for the supplied month. The method invocation is never skipped even if the cache headlines for the supplied month already existed.
6 Method invocation causes the invalidation of the cache headlines for the supplied month.
If you don’t annotate the class with @CacheConfig, specify the cache name in the cache annotations. E.g. @Cacheable(value = "headlines", parameters = {"month"})

2.3 Test the Cache

We can verify that the cache works as expected:

src/test/groovy/micronaut/example/micronaut/NewsServiceSpec.groovy
package example.micronaut

import io.micronaut.test.annotation.MicronautTest
import spock.lang.Specification
import spock.lang.Stepwise
import spock.lang.Timeout

import javax.inject.Inject
import java.time.Month

@Stepwise (1)
@MicronautTest (2)
class NewsServiceSpec extends Specification {

    @Inject (3)
    NewsService newsService;

    @Timeout(4) (4)
    void "first invocation of November does not hit cache"() {
        when:
        List<String> headlines = newsService.headlines(Month.NOVEMBER)

        then:
        2 == headlines.size()
    }

    @Timeout(1) (4)
    void "second invocation of November hits Cache"() {
        when:
        List<String> headlines = newsService.headlines(Month.NOVEMBER)

        then:
        2 == headlines.size()
    }

    @Timeout(4) (4)
    void "first invocation of October does not hit Cache"() {
        when:
        List<String> headlines = newsService.headlines(Month.OCTOBER)

        then:
        1 == headlines.size()
    }

    @Timeout(1) (4)
    void "second invocation of october hits cache"() {
        when:
        List<String> headlines = newsService.headlines(Month.OCTOBER)

        then:
        1 == headlines.size()
    }

    @Timeout(1) (4)
    void "adding a headline to november updates cache"() {
        when:
        List<String> headlines = newsService.addHeadline(Month.NOVEMBER, "Micronaut 1.3 Milestone 1 Released")

        then:
        3 == headlines.size()
    }

    @Timeout(1) (4)
    void novemberCacheWasUpdatedByCachePutAndThusTheValueIsRetrievedFromTheCache() {
        when:
        List<String> headlines = newsService.headlines(Month.NOVEMBER)

        then:
        3 == headlines.size()
    }

    @Timeout(1) (4)
    void "invalidate november cache with cache invalidate"() {
        when:
        newsService.removeHeadline(Month.NOVEMBER, "Micronaut 1.3 Milestone 1 Released")

        then:
        noExceptionThrown()
    }

    @Timeout(1) (4)
    void "october cache is still valid"() {
        when:
        List<String> headlines = newsService.headlines(Month.OCTOBER)

        then:
        1 == headlines.size()
    }

    @Timeout(4) (4)
    void "november cache was invalidated"() {
        when:
        List<String> headlines = newsService.headlines(Month.NOVEMBER)

        then:
        2 == headlines.size()
    }
}
1 Indicates that a spec’s feature methods should be run sequentially in their declared order.
2 Annotation used to define a Micronaut test
3 Inject NewsService bean.
4 Timeout annotation fails a test if its execution exceeds a given duration. It helps us verify that we are leaveraging the cache.

2.4 Controller

Create a controller which engages the previous service:

src/main/groovy/micronaut/example/micronaut/News.groovy
package example.micronaut

import io.micronaut.core.annotation.Introspected

import java.time.Month

@Introspected
class News {
    Month month
    List<String> headlines
}
src/main/groovy/micronaut/example/micronaut/NewsController.groovy
package example.micronaut

import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get

import java.time.Month

@Controller
class NewsController {

    private final NewsService newsService

    NewsController(NewsService newsService) {
        this.newsService = newsService
    }

    @Get('/{month}')
    News index(Month month) {
        new News(month: month, headlines: newsService.headlines(month))
    }
}

Add a test:

src/test/groovy/micronaut/example/micronaut/NewsControllerSpec.groovy
package example.micronaut

import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.uri.UriBuilder
import io.micronaut.runtime.server.EmbeddedServer
import io.micronaut.test.annotation.MicronautTest
import spock.lang.Specification
import spock.lang.Timeout

import javax.inject.Inject
import java.time.Month

@MicronautTest
class NewsControllerSpec extends Specification {

    @Inject
    EmbeddedServer server

    @Inject
    @Client("/")
    HttpClient client

    @Timeout(4) (1)
    void "fetching october headlines uses cache"() {
        given:
        String expected = "Micronaut AOP: Awesome flexibility without the complexity"

        when:
        HttpRequest request = HttpRequest.GET(UriBuilder.of("/").path(Month.OCTOBER.toString()).build())
        News news = client.toBlocking().retrieve(request, News)

        then:
        [expected] == news.headlines

        when:
        news = client.toBlocking().retrieve(request, News)

        then:
        [expected] == news.headlines
    }
}
1 We call the endpoint twice and verify with the @Timeout annotation that the cache is being used.

3 Where To Go From Here?

Read about Micronaut’s Cache Advise. Moreover, check the Micronaut Cache project for more information.

4 Help with Micronaut

OCI sponsored the creation of this Guide. OCI offers several Micronaut services:

Free consultation

The OCI Micronaut Team includes Micronaut co-founders, Jeff Scott Brown and Graeme Rocher. Check our Micronaut courses and learn from the engineers who developed, matured and maintain Micronaut.

Micronaut OCI Team