@Target(value={ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributeLock {
String key();
long expire();
int tryTimes();
long waitInterval();
}
1.2 编写切面
@Slf4j
@Component
@Aspect
public class LockAspect {
@Autowired
private JedisClient jedisClient;
@Around("execution(* *..*.*(..)) && @annotation(com.demo.distribute.lock.annotation.DistributeLock)")
public Object execute(ProceedingJoinPoint point) {
//读取接口方法签名
Method method = ((MethodSignature)point.getSignature()).getMethod();
DistributeLock distributeLock = method.getAnnotation(DistributeLock.class);
String key = distributeLock.key();
long expire = distributeLock.expire();
int tryTimes = distributeLock.tryTimes();
long waitInterval = distributeLock.waitInterval();
String value = UUID.randomUUID().toString();
try {
while(tryTimes -- > 0) {
if(jedisClient.setnx(key, value, expire)) {
return point.proceed();
}
Thread.sleep(waitInterval);
}
}catch(Throwable e) {
log.info("execute method error, e:", e);
}finally {
jedisClient.del(key, value);
}
return null;
}
}
1.3 测试代码
public class Consumer {
@DistributeLock(key = "distributeLockSecondKill", expire = 1000, tryTimes = 10, waitInterval = 10)
public void secondKill() {
int num = Good.getNum();
if(num -- > 0) {
System.out.println(Thread.currentThread().getName() + "抢到商品,商品剩余:" + num);
Good.setNum(num);
}
}
}
输出
Thread-10抢到商品,商品剩余:9 Thread-23抢到商品,商品剩余:8 Thread-60抢到商品,商品剩余:7 Thread-81抢到商品,商品剩余:6 Thread-80抢到商品,商品剩余:5 Thread-63抢到商品,商品剩余:4 Thread-84抢到商品,商品剩余:3 Thread-13抢到商品,商品剩余:2 Thread-79抢到商品,商品剩余:1 Thread-16抢到商品,商品剩余:02 redisson实现分布式锁



