概述
在使用自定义注解形式的@redis做缓存时,@redis失效,分析原因。实例
应用商店中根据imeiSnCode来查询安装列表
源代码
@Service("installedRecordService")
public class InstalledRecordServiceImpl implements InstalledRecordService{
@Resource
private InstalledRecordMapper installedRecordMapper;
@Override
public void getInstalledApks() {
List<String> imeiSnCodes = installedRecordMapper.queryImeiCode();
if (imeiSnCodes != null && imeiSnCodes.size()> 0) {
for(int i=0;i<imeiSnCodes.size();i++){
getInstalledApk(imeiSnCodes.get(i));
}
}
}
@Redis(value=RedisKeys.INSTALLED_APK,keyArgs={0},sync=true,cacheNull=false,ttl=Constants.INSTALLED_APK_TIME,action=RedisAction.STAB_REDIS)
public List<InstalledRecord> getInstalledApk(final String code){
return installedRecordMapper.listByImeiSnCode(code);
}
}
但是发现缓存不成功。
原因
Aop的原理图如下:
![](https://i-blog.csdnimg.cn/blog_migrate/df7c616ea4f58701634f3fa2d91ad0a0.png)
也就是说我们首先调用的是AOP代理对象而不是目标对象。但是我们使用this.getInstalledApk(imeiSnCodes.get(i))时,this表示的是当前的对象,而不是代理对象,因此注解失效。
解决方法
解决方法1
将getInstalledApks()方法放在另外的一个类中进行调用,就不会出现这种问题了。代码省略。解决方法2
暴露AOP代理对象:<aop:aspectj-autoproxy expose-proxy="true"/>
仍然在同一个类中调用代码,但是改为如下的形式:
@Service("installedRecordService")
public class InstalledRecordServiceImpl implements InstalledRecordService{
@Resource
private InstalledRecordMapper installedRecordMapper;
@Override
public void getInstalledApks() {
List<String> imeiSnCodes = installedRecordMapper.queryImeiCode();
if (imeiSnCodes != null && imeiSnCodes.size()> 0) {
for(int i=0;i<imeiSnCodes.size();i++){
//获取当前代理对象,进行调用
((InstalledRecordService) AopContext.currentProxy()).getInstalledApk(imeiSnCodes.get(i));
}
}
}
}
原理:AopContext的实现:
public abstract class AopContext {
private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal<Object>("Current AOP proxy");
public static Object currentProxy() throws IllegalStateException {
Object proxy = currentProxy.get();
if (proxy == null) {
throw new IllegalStateException(
"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
}
return proxy;
}
static Object setCurrentProxy(Object proxy) {
Object old = currentProxy.get();
if (proxy != null) {
currentProxy.set(proxy);
}
else {
currentProxy.remove();
}
return old;
}
}
(1)在进入代理对象之后通过AopContext.serCurrentProxy(proxy)暴露当前代理对象到ThreadLocal,并保存上次ThreadLocal绑定的代理对象为oldProxy
(2)接下来我们可以通过 AopContext.currentProxy() 获取当前代理对象;
(3)在退出代理对象之前要重新将ThreadLocal绑定的代理对象设置为上一次的代理对象,即AopContext.serCurrentProxy(oldProxy)。
解决方法3
往实现类中注入自身。仍然在同一个类中调用代码,但是改为如下的形式:
@Service("installedRecordService")
public class InstalledRecordServiceImpl implements InstalledRecordService{
//注入自身
@Resource
private InstalledRecordService installedRecordService;
@Resource
private InstalledRecordMapper installedRecordMapper;
@Override
public void getInstalledApks() {
List<String> imeiSnCodes = installedRecordMapper.queryImeiCode();
if (imeiSnCodes != null && imeiSnCodes.size()> 0) {
for(int i=0;i<imeiSnCodes.size();i++){
installedRecordService.getInstalledApk(imeiSnCodes.get(i));
}
}
}