Micronaut Cache

Learn how to use Micronaut caching annotations

Authors: Sergio del Amo

Micronaut Version: 4.4.0

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=kotlin
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/kotlin/example/micronaut/NewsService.kt
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 java.time.Month
import java.util.concurrent.TimeUnit
import jakarta.inject.Singleton

@Singleton (1)
@CacheConfig("headlines") (2)
open class NewsService {
    val headlines = mutableMapOf(
            Month.NOVEMBER to listOf("Micronaut Graduates to Trial Level in Thoughtworks technology radar Vol.1",
            "Micronaut AOP: Awesome flexibility without the complexity"),
            Month.OCTOBER to listOf("Micronaut AOP: Awesome flexibility without the complexity"))

    @Cacheable (3)
    open fun headlines(month: Month): List<String>? {
        return try {
            TimeUnit.SECONDS.sleep(3) (4)
            headlines[month]
        } catch (e: InterruptedException) {
            null
        }
    }

    @CachePut(parameters = ["month"]) (5)
    open fun addHeadline(month: Month, headline: String): List<String>? {
        val l = headlines.getOrDefault(month, emptyList()).toMutableList()
        l.add(headline)
        headlines[month] = l
        return headlines[month]
    }

    @CacheInvalidate(parameters = ["month"]) (6)
    open fun removeHeadline(month: Month, headline: String?) {
        val l = headlines.getOrDefault(month, emptyList()).toMutableList()
        l.remove(headline)
        headlines[month] = l
    }
}
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/kotlin/example/micronaut/NewsServiceTest.kt
package example.micronaut

import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation
import org.junit.jupiter.api.Order
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestMethodOrder
import org.junit.jupiter.api.Timeout
import java.time.Month
import jakarta.inject.Inject

@TestMethodOrder(OrderAnnotation::class) (1)
@MicronautTest(startApplication = false)  (2)
internal class NewsServiceTest {
    @Inject
    lateinit var newsService : NewsService (3)

    @Timeout(4) (4)
    @Test
    @Order(1) (5)
    fun firstInvocationOfNovemberDoesNotHitCache() {
        val headlines = newsService.headlines(Month.NOVEMBER)
        assertEquals(2, headlines!!.size)
    }

    @Timeout(1) (4)
    @Test
    @Order(2) (5)
    fun secondInvocationOfNovemberHitsCache() {
        val headlines = newsService.headlines(Month.NOVEMBER)
        assertEquals(2, headlines!!.size)
    }

    @Timeout(4) (4)
    @Test
    @Order(3) (5)
    fun firstInvocationOfOctoberDoesNotHitCache() {
        val headlines = newsService.headlines(Month.OCTOBER)
        assertEquals(1, headlines!!.size)
    }

    @Timeout(1) (4)
    @Test
    @Order(4) (5)
    fun secondInvocationOfOctoberHitsCache() {
        val headlines = newsService.headlines(Month.OCTOBER)
        assertEquals(1, headlines!!.size)
    }

    @Timeout(1) (4)
    @Test
    @Order(5) (5)
    fun addingAHeadlineToNovemberUpdatesCache() {
        val headlines = newsService.addHeadline(Month.NOVEMBER, "Micronaut 1.3 Milestone 1 Released")
        assertEquals(3, headlines!!.size)
    }

    @Timeout(1) (4)
    @Test
    @Order(6) (5)
    fun novemberCacheWasUpdatedByCachePutAndThusTheValueIsRetrievedFromTheCache() {
        val headlines = newsService.headlines(Month.NOVEMBER)
        assertEquals(3, headlines!!.size)
    }

    @Timeout(1) (4)
    @Test
    @Order(7) (5)
    fun invalidateNovemberCacheWithCacheInvalidate() {
        assertDoesNotThrow { newsService.removeHeadline(Month.NOVEMBER, "Micronaut 1.3 Milestone 1 Released") }
    }

    @Timeout(1) (4)
    @Test
    @Order(8) (5)
    fun octoberCacheIsStillValid() {
        val headlines = newsService.headlines(Month.OCTOBER)
        assertEquals(1, headlines!!.size)
    }

    @Timeout(4) (4)
    @Test
    @Order(9) (5)
    fun novemberCacheWasInvalidated() {
        val headlines = newsService.headlines(Month.NOVEMBER)
        assertEquals(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.
5 Used to configure the order in which the test method should executed relative to other tests in the class.

4.4. Controller

Create a controller which engages the previous service:

src/main/kotlin/example/micronaut/News.kt
package example.micronaut

import io.micronaut.serde.annotation.Serdeable
import java.time.Month

@Serdeable (1)
data class News(val month: Month, val headlines: List<String>)
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
src/main/kotlin/example/micronaut/NewsController.kt
package example.micronaut

import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import java.time.Month

@Controller (1)
class NewsController(val newsService: NewsService) {
    @Get("/{month}")
    fun index(month: Month): News {
        return News(month, newsService.headlines(month).orEmpty())
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.

Add a test:

src/test/kotlin/example/micronaut/NewsControllerTest.kt
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.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout
import java.time.Month
import jakarta.inject.Inject

@MicronautTest
class NewsControllerTest(@Client("/") val client: HttpClient) {

    @Timeout(5) (1)
    @Test
    fun fetchingOctoberHeadlinesUsesCache() {
        val request: HttpRequest<Any> = HttpRequest.GET(UriBuilder.of("/").path(Month.OCTOBER.name).build())
        var news: News = client.toBlocking().retrieve(request, News::class.java)
        val expected = "Micronaut AOP: Awesome flexibility without the complexity"
        assertEquals(listOf(expected), news.headlines)
        news = client.toBlocking().retrieve(request, News::class.java)
        assertEquals(listOf(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. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.

Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.

Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

6.1. GraalVM installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 17
sdk install java 17.0.8-graal
Java 17
sdk use java 17.0.8-graal

For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 17
sdk install java 17.0.8-graalce
Java 17
sdk use java 17.0.8-graalce

6.2. Native executable generation

To generate a native executable using Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle
graalvmNative {
    binaries {
        main {
            imageName.set('mn-graalvm-application') (1)
            buildArgs.add('--verbose') (2)
        }
    }
}
1 The native executable name will now be mn-graalvm-application
2 It is possible to pass extra arguments to build the native executable

You should be able to execute this curl request and see results:

curl localhost:8080/NOVEMBER

7. Next steps

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

8. Help with the Micronaut Framework

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

9. 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…​).