How to implement a method cache in java

I would like to create my own annotation to cache the results obtained 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 result of a method.
@InvalidateMethodCache: clear cache.

+3


source to share


4 answers


I have implemented method cache using spring / java ..



https://github.com/vikashnitk50/spring-application-caching/

0


source


The solution when using spring-aop is to create an aspect to handle all the methods annotated with your custom annotation. A rough 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());
}

      

+2


source


Ok if you have ready made annotations available, it is better to use them
Although you can follow this, I hope this helps you

  • Implement the CacheAnnotationParser interface
  • expand AnnotationCacheOperationSource to add a CacheAnnotationParser in addition to Spring in the internal parser collection
  • Define your own AnnotationCacheOperationSource to use the same identifier as Spring, so it will override the Spring internal. If the id is the same, it should override Spring one purely.

    Like this one :

+2


source


I have implemented this functionality and uploaded my project to GITHUB .

Example:

public class CountryService {

    @MethodCache

    public List<Country> getCountries();


    @MethodCache

    public Country getCountryById(int countryId);

    @InvalidateMethodCache

    public Country deleteCountryByID(int countryId);

  }

      

+2


source







All Articles