mn create-app example.micronaut.micronautguide --build=gradle --lang=java
Micronaut Cache
Learn how to use Micronaut caching annotations
Authors: Sergio del Amo
Micronaut Version: 3.9.2
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:
-
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 application step by step. However, you can go right to the completed example.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
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.
|
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.
implementation("io.micronaut.cache:micronaut-cache-caffeine")
Configure your caches in 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.
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 jakarta.inject.Singleton;
import java.time.Month;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Singleton (1)
@CacheConfig("headlines") (2)
public class NewsService {
Map<Month, List<String>> headlines = new HashMap<Month, List<String>>() {{
put(Month.NOVEMBER, Arrays.asList("Micronaut Graduates to Trial Level in Thoughtworks technology radar Vol.1",
"Micronaut AOP: Awesome flexibility without the complexity"));
put(Month.OCTOBER, Collections.singletonList("Micronaut AOP: Awesome flexibility without the complexity"));
}};
@Cacheable (3)
public List<String> headlines(Month month) {
try {
TimeUnit.SECONDS.sleep(3); (4)
return headlines.get(month);
} catch (InterruptedException e) {
return null;
}
}
@CachePut(parameters = {"month"}) (5)
public List<String> addHeadline(Month month, String headline) {
if (headlines.containsKey(month)) {
List<String> l = new ArrayList<>(headlines.get(month));
l.add(headline);
headlines.put(month, l);
} else {
headlines.put(month, Arrays.asList(headline));
}
return headlines.get(month);
}
@CacheInvalidate(parameters = {"month"}) (6)
public void removeHeadline(Month month, String headline) {
if (headlines.containsKey(month)) {
List<String> l = new ArrayList<>(headlines.get(month));
l.remove(headline);
headlines.put(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:
package example.micronaut;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.MethodOrderer;
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 jakarta.inject.Inject;
import java.time.Month;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) (1)
@MicronautTest(startApplication = false) (2)
class NewsServiceTest {
@Inject (3)
NewsService newsService;
@Timeout(4) (4)
@Test
@Order(1) (5)
public void firstInvocationOfNovemberDoesNotHitCache() {
List<String> headlines = newsService.headlines(Month.NOVEMBER);
assertEquals(2, headlines.size());
}
@Timeout(1) (4)
@Test
@Order(2) (5)
public void secondInvocationOfNovemberHitsCache() {
List<String> headlines = newsService.headlines(Month.NOVEMBER);
assertEquals(2, headlines.size());
}
@Timeout(4) (4)
@Test
@Order(3) (5)
public void firstInvocationOfOctoberDoesNotHitCache() {
List<String> headlines = newsService.headlines(Month.OCTOBER);
assertEquals(1, headlines.size());
}
@Timeout(1) (4)
@Test
@Order(4) (5)
public void secondInvocationOfOctoberHitsCache() {
List<String> headlines = newsService.headlines(Month.OCTOBER);
assertEquals(1, headlines.size());
}
@Timeout(1) (4)
@Test
@Order(5) (5)
public void addingAHeadlineToNovemberUpdatesCache() {
List<String> headlines = newsService.addHeadline(Month.NOVEMBER, "Micronaut 1.3 Milestone 1 Released");
assertEquals(3, headlines.size());
}
@Timeout(1) (4)
@Test
@Order(6) (5)
public void novemberCacheWasUpdatedByCachePutAndThusTheValueIsRetrievedFromTheCache() {
List<String> headlines = newsService.headlines(Month.NOVEMBER);
assertEquals(3, headlines.size());
}
@Timeout(1) (4)
@Test
@Order(7) (5)
public void invalidateNovemberCacheWithCacheInvalidate() {
assertDoesNotThrow(() -> {
newsService.removeHeadline(Month.NOVEMBER, "Micronaut 1.3 Milestone 1 Released");
});
}
@Timeout(1) (4)
@Test
@Order(8) (5)
public void octoberCacheIsStillValid() {
List<String> headlines = newsService.headlines(Month.OCTOBER);
assertEquals(1, headlines.size());
}
@Timeout(4) (4)
@Test
@Order(9) (5)
public void novemberCacheWasInvalidated() {
List<String> 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:
package example.micronaut;
import io.micronaut.serde.annotation.Serdeable;
import java.time.Month;
import java.util.List;
@Serdeable (1)
public class News {
private Month month;
private List<String> headlines;
public News() {
}
public News(Month month, List<String> headlines) {
this.month = month;
this.headlines = headlines;
}
public Month getMonth() {
return month;
}
public void setMonth(Month month) {
this.month = month;
}
public List<String> getHeadlines() {
return headlines;
}
public void setHeadlines(List<String> headlines) {
this.headlines = headlines;
}
}
1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
package example.micronaut;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import java.time.Month;
@Controller (1)
public class NewsController {
private final NewsService newsService;
public NewsController(NewsService newsService) {
this.newsService = newsService;
}
@Get("/{month}")
public News index(Month month) {
return new News(month, newsService.headlines(month));
}
}
1 | The class is defined as a controller with the @Controller annotation mapped to the path / . |
Add a test:
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.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import jakarta.inject.Inject;
import java.time.Month;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
@MicronautTest
public class NewsControllerTest {
@Inject
EmbeddedServer server;
@Inject
@Client("/")
HttpClient client;
@Timeout(5) (1)
@Test
void fetchingOctoberHeadlinesUsesCache() {
HttpRequest request = HttpRequest.GET(UriBuilder.of("/").path(Month.OCTOBER.name()).build());
News news = client.toBlocking().retrieve(request, News.class);
String expected = "Micronaut AOP: Awesome flexibility without the complexity";
assertEquals(Arrays.asList(expected), news.getHeadlines());
news = client.toBlocking().retrieve(request, News.class);
assertEquals(Arrays.asList(expected), news.getHeadlines());
}
}
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. Native executable generation
The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.
sdk install java 22.3.r11-grl
If you still use Java 8, use the JDK11 version of GraalVM. |
sdk install java 22.3.r17-grl
For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
After installing GraalVM, install the native-image
component, which is not installed by default:
gu install native-image
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:
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.