Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we implement method cache in java

I'd like to design my own annotation in order to cache results retrieved from an earlier database call.

For example:

public class CountryService {
 @MethodCache
 public List<Country> getCountries();

 @MethodCache
 public Country getCountryById(int countryId);

 @InvalidateMethodCache
 public Country getCountryById(int countryId);

}

I want to use this type of annotation for more/all of my methods. What do I need to implement this type of annotation?

@MethodCache: Cache the method result.
@InvalidateMethodCache: Clear the cache.

like image 666
VIKASH SINHA Avatar asked Apr 07 '26 15:04

VIKASH SINHA


2 Answers

A solution when using spring-aop is to create an aspect to handle all methods annotated with your custom annotation. An crude implementation would look like this:

Map<String, Object> methodCache = new HahsMap<>();

@Around("execution(@(@com.mypack.MethodCache *) *)")
public Object cacheMethod(ProceedingJoinPoint pjp) {
     String cacheKey = getCacheKey(pjp);
     if ( methodCache.get(cacheKey)) {
          return methodCache.get(cacheKey);
     } else {
          Object result = pjp.proceed();
          methodCache.put(cacheKey, result);
          return result;
     }
}

private String getCacheKey(ProceedingJoinPoint pjp) {
     return pjp.getSignature().toString() + pjp.getTarget() + Arrays.asList(pjp.getArgs());
}
like image 175
6ton Avatar answered Apr 10 '26 03:04

6ton


Well if have ready available annotaions,Better use them
While you can follow this, I hope this guides you

  • Implement the interface CacheAnnotationParser
  • extend AnnotationCacheOperationSource so that you put your own CacheAnnotationParser in addition to Spring one in the internal parsers collection
  • Define your custom AnnotationCacheOperationSource to use the same id as Spring one does, so it will override Spring internal. If id matches, it should override Spring one cleanly.

    Like this:

like image 25
VeKe Avatar answered Apr 10 '26 04:04

VeKe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!