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.
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());
}
Well if have ready available annotaions,Better use them
While you can follow this, I hope this guides you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With