Skip to content

Add @OnCacheHit annotation to intercept the cache hit #33642

@mipo256

Description

@mipo256

There is a common requirement to perform some actions in case cache was hit, for instance to log the actual hit, as in the mentioned issue.

For logging purposes, for instance:

  1. Enable detailed logging for the org.springframework.cache, which is not very convenient, since the log is predefined and cannot be customized.
  2. Or we can use Cache/CacheManager directly. For instance, something like that:
var resp = cache.get(dto.getKey(), DomainClass.class);
if (resp != null) {
  log.info("Return entities for client : {} from cache by key : {}", clientId, dto.getKey());
  return Either.right(resp);
}
log.info("Request entities for clientId {} with key {} from original service", clientId, dto.getKey());
return delegate
    .getEntities(dto, clientId)
    .peek(responseDto -> cache.put(dto.getKey(), responseDto));

That of course can be done, but if you think about it, this turmoil is required here because of one simple thing - we want to log the cache hit.

Proposal:

I think it would be a good idea to introduce an annotation, such as @OnCacheHit(cacheName="something", unless="SPEL")
This would've clearly made the code above unnecessary, becuase we can just do:

@OnCacheHit(cacheName="my-cache")
// args - original method arguments
void logHit(Object[] args) {
  log.info("Return entities for client : {} from cache by key : {}", args[0], args[1]);
}

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: declinedA suggestion or change that we don't feel we should currently apply

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions