Micronaut Cache

Learn how to use Micronaut caching annotations

Authors: Sergio del Amo

Micronaut Version: 4.3.7

1. Getting Started

In this guide, you will use Micronaut caching annotations to speed up your application.

2. What you will need

To complete this guide, you will need the following:

3. Solution

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

4. Writing the Application

Create an application 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 the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory 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 jakarta.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 Use jakarta.inject.Singleton to designate a class as a 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 annotation.
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 exists.
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 jakarta.inject.Inject
import java.time.Month

@Stepwise (1)
@MicronautTest(startApplication = false)  (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 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
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.serde.annotation.Serdeable

import java.time.Month

@CompileStatic
@Serdeable (1)
class News {
    Month month
    List<String> headlines
}
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
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 (1)
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))
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.

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 jakarta.inject.Inject
import java.time.Month

@MicronautTest
class NewsControllerSpec extends Specification {

    @Inject
    EmbeddedServer server

    @Inject
    @Client("/")
    HttpClient client

    @Timeout(5) (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 starts the application on port 8080.

6. Next steps

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

7. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

8. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).