How to detect if @Cacheable method output comes from cache?
Asked Answered
M

2

6

There is a method annotated with @Cacheable that returns an object:

@Service
public class UserService {

  @Cacheable("userData")
  public UserData getUserData(String userName) {
    UserData userData = new UserData();
    userData.setGotFromCache(false);
    return userData;
  }

}

And the UserData object:

@Getter
@Setter
public class UserData {
  private boolean gotFromCache;
}

How to detect whether method annotated @Cacheable was called or whether its output comes from cache?

The workaround is to inject CacheManager and detect it manually:

Cache cache = this.cacheManager.getCache("userData");
UserData userData = null;
String userName = "some user name";
if (cache != null) {
  Object key = SimpleKeyGenerator.generateKey(userName);
  userData = cache.get(key, UserData.class);
  if (userData != null) {
    userData.setGotFromCache(true);
  } else {
    userData = userService.getUserData(userName);
    cache.put(key, userData);
  }
} else {
  userData = userService.getUserData(userName);
}

However, this code doesn't utilize @Cacheable annotation for the simplicity.

Is it possible to use @Cacheable and detect whether output comes from cache?

Mandell answered 12/9, 2019 at 8:45 Comment(0)
N
0

Depends on when you need to detect - at runtime when the application is deployed, or during development.

Either way, the basic idea is same: there must be an underlying data source such as a database (UserRepository?) or API call or something else.

At runtime, you can check if the the data source is invoked, either via logging or tracing (eg using Zipkin).

--or--

During development, you can write unit tests for UserService that mock the datasource, and verify that there were "zero interactions" with the mock object, indicating that the data was in fact fetched from cache.

Nonlinearity answered 12/9, 2019 at 14:11 Comment(0)
C
0

You can change the userdata and see if the value returned is the old one or the new one

Coarse answered 12/9, 2019 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.