Skip to content

Instrument @Cacheable for observability #34219

@patpatpat123

Description

@patpatpat123

** Enhancements requests **

To Reproduce

Here is the code:

@Configuration
@EnableCaching
public class CacheConfig {

  @Bean
  public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();
    Cache<Object, Object> cache = Caffeine.newBuilder().recordStats().build();
    cacheManager.registerCustomCache("test", cache);
    return cacheManager;
  }

}
  @GetMapping("/getAnimal")
  public String getAnimal(@RequestParam String name) {
    LOGGER.info("caching " + name);
    String person = getAnimal(name);
    return person;
  }
 @Cacheable("AnimalCash")
  public String getAnimal(String name) {
    //LOG
    System.out.println("please see me only once to prove caching works: " + name);

    //expensice call here, hope cache will work
    ResponseEntity<Map> response = this.restClient.post()
            .uri("http://localhost:8081/returnObject")
            .body(Map.of("name", "azerty"))
            .retrieve()
            .toEntity(Map.class);
    return response.getBody().keySet().toString();
  }

(mock an expensive downstream service)

    @PostMapping("/justString")
    public String justString(@RequestParam String name) {
        System.out.println("please only see me once " + name);
        try {
            Thread.sleep(9000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return name.toUpperCase() + "test";
    }

As you can see, this is a straightforward piece of code, where there is the use of cacheable to cache an expensive http call.
The code is working, because the second call would get the data directly from the cache (checked there is no more call on the downstream service, the response comes very fast)

Expected behavior

For the traces, while it is technically correct that there is no trace for the network call, since it did not happen.
Can this be enhanced by showing a trace that it went to the cache?

Screen Shot 2024-12-20 at 00 59 39
Screen Shot 2024-12-20 at 01 03 20

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: coreIssues in core modules (aop, beans, core, context, expression)status: declinedA suggestion or change that we don't feel we should currently applytheme: observabilityAn issue related to observability and tracing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions