使用cblib代理模式,从而减少完成分布式锁的重复代码。
@Component
public class CGlibProxy implements MethodInterceptor {
//代理方法
public Object createProxy(Object target){
//创建一个动态类对象
Enhancer enhancer = new Enhancer();
//确定要增强的类,设置期父类
enhancer.setSuperclass(target.getClass());
//添加回调函数
enhancer.setCallback(this);
//返回创建的代理类
return enhancer.create();
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//key为类名加方法名
String key = method.getDeclaringClass().getName()+"_"+method.getName()+"_LOCK";
//获取分布式锁
boolean lock = redis.getLock(key);
Object obj ;
if (lock) {
//执行逻辑
obj=methodProxy.invokeSuper(o,objects);
redis.delete(key);
} else {
// 设置失败次数计数器, 当到达5次时, 返回失败
int count = 1;
while(c