Slevin
Slevin

Reputation: 1294

How to get information about which Cache Manager is used in a Spring Boot application?

In a Spring Boot application, even when I completely abstain from declaring a specific cache manager, using the @Cacheable annotation will work and serves cached entries. So I assume, that there is at least some simple HashMap caching system at work.

Now, how can I ensure that the intended caching system (e.g. Caffeine or Ehcache) is in place properly and serving my requests and not the cheap included one? Since the caching system is intercepting calls via proxy I quite don't know to set a breakpoint for this.

Is there any way to see which Cache Manager is working currently?

Upvotes: 1

Views: 2208

Answers (2)

samabcde
samabcde

Reputation: 8124

By referring Documentation

Springboot provide nice documentation about caching. Refer to section 1 Caching

If you do not add any specific cache library, Spring Boot auto-configures a simple provider that uses concurrent maps in memory.

To find out the cacheManager application is using, we could use actuator api on caches. Assume the actuator is setup and caches endpoint is exposed. When we go to http://localhost:8080/actuator/caches, you will see something like below:

{
  "cacheManagers": {
    "cacheManager": {
      "caches": {
        "nameCache": {
          "target": "java.util.concurrent.ConcurrentHashMap"
        }
      }
    }
  }
}

By digging into the code

Since the caching system is intercepting calls via proxy I quite don't know to set a breakpoint for this.

Using break point is a more generic approach, but usually more difficult. I will consider this to be the last method to try. (Do try it when you run out of idea, you will definitely gain something by tracing through the code)

Below are the steps I will perform

  • Put a breakpoint inside the @Cacheable method,
  • It will hit for the first invocation, then look into the call stack,
  • Find cache related class/package from spring
  • Try understand the flow, put breakpoint to somewhere you interested, and rerun the program

Upvotes: 2

lane.maxwell
lane.maxwell

Reputation: 5893

Yes, the default cache mechanism is some HashMap, implemented in ConcurrentMapCacheManager. I suppose the most straightforward means for verifying that you are getting the CacheManager you expect would be something like this.

Create a service and inject the CachManager into it, and create a PostConstruct method to check that it's the one you want.

@Service
public class CacheVerifier {
  private final CacheManager cacheManager;

  public CacheVerifier(CacheManager cacheManager) {
    this.cacheManager = cacheManager;
  }

  @PostConstruct
  public void verify() {
    assert this.cacheManager instanceof CaffeineCacheManager;
  }
}

Upvotes: 3

Related Questions