Referencing Variables in Micronaut Caches

Viewed 190

I was wondering how to include Path variables in the Micronaut caching annotation.

Example:

@Get("/test/{name}")
public String getName(@PathVariable String name){
  return "Hello " + name;
}

Now imagine this would be some computationally expensive operation for a user. Obviously, I have to include the user name in the cache key to be able to retrieve or invalidate it. Sadly I havent found any docs on this, so maybe someone here has a clue.

1 Answers

If you really want to cache the controller endpoint itself (as opposed to a service it is delegating to), you could configure the cache in application.yml:

micronaut:
  application:
    name: yourapp
  caches:
    somecachename:
      expire-after-write: 30m
      maximum-size: 10

Then use that cache:

import io.micronaut.cache.annotation.Cacheable;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;

@Controller("/demo")
public class DemoController {

    @Get("/test/{name}")
    @Cacheable("somecachename")
    public String getName(@PathVariable String name) {
        System.out.println("Here we are " + name);
        return "Hello " + name;
    }
}

You will need a dependency on whatever cache you are using, for example, to use caffeine:

implementation("io.micronaut.cache:micronaut-cache-caffeine")
Related