public class CouponController {
@Autowired
private StringRedisTemplate redisTemplate;
@GetMapping("add")
public JsonData saveCoupon(@RequestParam(value = "coupon_id",required = true) int couponId){
String uuid = UUID.randomUUID().toString();
String lockKey = "lock:coupon:"+couponId;
lock(couponId,uuid,lockKey);
return JsonData.buildSuccess();
}
private void lock(int couponId,,String uuid,String lockKey){
// String uuid = UUID.randomUUID().toString();
// String lockKey = "lock:coupon:"+couponId;
//lua脚本
String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
Boolean nativeLock = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, Duration.ofSeconds(30));
System.out.println("加锁状态");
if (nativeLock){
// 加锁成功
try {
//TODO 做相关业务逻辑
TimeUnit.SECONDS.sleep(10L);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//解锁
Long result = redisTemplate.execute(new DefaultRedisscript<>(script, Long.class), Arrays.asList(lockKey), uuid);
System.out.println(uuid+"解锁状态"+result);
}
}else {
//自旋操作
try {
System.out.println("加锁失败,进入自旋");
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock(couponId,uuid,lockKey);
}
}
}