如果你只是想使用一个轻量级的缓存方案,那么可以尝试使用Spring cache方案。那么在使用spring @Cacheable注解的时候,要注意,如果类A的方法f()被标注了@Cacheable注解,那么当类A的其他方法,例如:f2(),去直接调用f()的时候,@Cacheable是不起作用的,原因是@Cacheable是基于spring aop代理类,f2()属于内部方法,直接调用f()时,是不走代理的。举个例子:
@Cacheable(key = "#entityType", value = "xxxCache")
public List<String selectByEntityType(intentityType) {
List<String> result = new ArrayList<>();
return result;
}
public List<String> f2(){
selectByEntityType(1);
}
可以把selectByEntityType方法抽取到另外的类中,例如:
@Service
public class CacheService{
@Cacheable(key = "#entityType", value = "xxxCache")
public List<String selectByEntityType(intentityType) {
List<String> result = new ArrayList<>();
return result;
}
}
这样其他类要使用selectByEntityType方法,只能注入CacheService,走代理。