场景:抢购
1.控制器层
了解一下或许有帮助:分布式开发杂谈
/**
* 抢购
* */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
@Autowired
private RedisNxUtil redisNxUtil;
/**
* 分布式锁实现抢购
* 2020-04-14
* */
@RequestMapping(value = "/buy", method = RequestMethod.POST)
public void buy(Integer uid, @RequestBody BuyDto buyRequest) {
if (uid == null) {
throw new AppException(FinancialCodeConst.NO_LOGIN);
}
// 获取锁的key,原则是同一个抢购使用同一个锁
String key = "FinancialProduct:" + buyRequest.getProductId();
// 获取锁,即添加一个锁
boolean lock = redisNxUtil.lock(key);
if (lock) {
try {
// 允许执行本次购买,开始购买
buyProduct(buyRequest, uid);
} catch (Exception e) {
throw e;
} finally {
redisNxUtil.delete(key);
}
} else {
// 若没有获取到锁,则表示当前锁已被占用,等待再次获取锁
int failCount = 1;
// 记录是否成功获取锁,防止成功后再次进入循环
boolean isSuccess = false;
// 设置失败次数计数器, 当到达5次时, 返回失败
while (failCount <= 5 && !isSuccess) {
// 等待100ms重试
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (redisNxUtil.lock(key)) {
try {
// 允许执行本次购买,开始购买
buyProduct(buyRequest, uid);
} catch (Exception e) {
throw e;
} finally {
redisNxUtil.delete(key);
}
isSuccess = true;
} else {
failCount++;
}
}
if (!isSuccess) {
throw new AppException("当前购买人数太多请稍后重试");
}
}
}
/**
* 开始购买
*/
private void buyProduct(BuyDto buyRequest, Integer uid) {
...
}
}
2.Redis的锁处理
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
/**
* RedisNXUtil
*/
@Component
public class RedisNxUtil {
public static final String LOCK_PREFIX = "REDIS_NX_LOCK";
/**
* ms
*/
public static final int LOCK_EXPIRE = 300;
@Autowired
private RedisTemplate redisTemplate;
/**
* 分布式锁(防止死锁)
*
* @param key key
* @return 是否获取到
*/
public boolean lock(String key) {
String lock = LOCK_PREFIX + ":" + key;
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
long exprieAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(exprieAt).getBytes());
if (acquire) {
return true;
} else {
byte[] value = connection.get(lock.getBytes());
if (Objects.nonNull(value) && value.length > 0) {
long expireTime = Long.parseLong(new String(value));
if (expireTime < System.currentTimeMillis()) {
// 如果锁已经过期
byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
// 防止死锁
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
});
}
/**
* 删除锁
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
}
3.php版本
原理和java是一致的
/**
* redis分布式锁
* @param $lock
* @param int $expireTime 过期时间:毫秒
* @return bool
*/
public function lock($lock, $expireTime = 5000)
{
$nowTimeMs = time() * 1000;
$expireAt = $nowTimeMs + $expireTime;
$acquire = $this->redis->setnx($lock, $expireAt);
if ($acquire) {
return true;
} else {
// 防止死锁
$oldValue = $this->redis->get($lock);
if (!$oldValue || $nowTimeMs > $oldValue) {
// 如果锁已经过期,这里需要注意getSet的用法
$lastValue = $this->redis->getSet($lock, $expireAt);
return $lastValue < $nowTimeMs;
}
return false;
}
}