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;
// 設置失敗次數計數器, 當到達5次時, 返回失敗
while (failCount <= 5) {
// 等待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);
}
} else {
failCount++;
}
}
throw new AppException(FinancialCodeConst.TOO_MANY_PEOPLE);
}
}
/**
* 開始購買
*/
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);
}
}