Micronaut Cache

Learn how to use Micronaut’s caching annotations

Authors: Sergio del Amo

Micronaut Version: 2.5.0

1. Getting Started

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

2. 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

3. Solution

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

4. Writing the App

Create an app using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide --build=gradle --lang=groovy
If you don’t specify the --build argument, Gradle is used as a build tool.
If you don’t specify the --lang argument, Java is used as a language.

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

4.1. Configure the Application

In this sample application, we cache news headlines. Add Micronaut Caffeine Cache dependency which adds support for cache using Caffeine.

build.gradle
implementation("io.micronaut.cache:micronaut-cache-caffeine")

Configure your caches in application.yml:

src/main/resources/application.yml
micronaut:
  caches:
    headlines: (1)
      charset: 'UTF-8'
1 Configure a cache called headlines.
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.

4.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 groovy.transform.CompileStatic
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

@CompileStatic
@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)) {
            List<String> lines = headlines[month]
            lines << headline
            headlines.put(month, lines)
        } else {
            headlines[month] = [headline]
        }
        headlines[month]
    }

    @CacheInvalidate(parameters = ["month"]) (6)
    void removeHeadline(Month month, String headline) {
        if (headlines.containsKey(month)) {
            List<String> lines = headlines[month]
            lines -= headline
            headlines.put(month, lines)
        }
    }
}
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"})

4.3. Test the Cache

We can verify that the cache works as expected:

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

import io.micronaut.test.extensions.spock.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 "november cache was updated by cache put and thus the value is retrieved from the cache"() {
        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 Used to configure the test method execution order for the annotated test class.
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.

4.4. Controller

Create a controller which engages the previous service:

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

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.Introspected

import java.time.Month

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

import groovy.transform.CompileStatic
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get

import java.time.Month

@CompileStatic
@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/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.extensions.spock.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.name())
                .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.

5. Running the Application

To run the application use the ./gradlew run command which will start the application on port 8080.

6. Next steps

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

7. Help with Micronaut

Object Computing, Inc. (OCI) sponsored the creation of this Guide. A variety of consulting and support services are available.