需求背景:
入库单号:L-ASN2025022xxxxx
入库批次号:100025022800151
数量:500
理货后,生成了一个500的已理货数据,上架后,生成了两个500已上架数据,重复了
后台查看数据创建时间也一样,仓库操作人员由于网络或者其他问题出现重复点击或者在多人操作同一单据情况下出现的并发问题
这种情况下仅仅针对接口加分布式锁解决不了实际问题,需要针对请求url,参数进行加锁才可以完全解决
以php项目为例 php-laravel框架
1,通过url+请求参数进行加锁处理 可以组织90%以上的重复点击带来的重复数据的问题
PreventDupSubmit.php
all();
$requestParams["adminId"] = getAdminUserId();
$requestParams["uri"] = $request->getUri();
if(isset($requestParams["file"])){
unset($requestParams["file"]);
}
\Log::info(sprintf("并发请求url:%s,请求参数:%s",$request->getUri(),json_encode($requestParams)));
ksort($requestParams);
$key = md5(serialize($requestParams));
$getLock = WmsLockService::getLock($key,8);
// $request->offsetSet("request_md5_key",$key);
if(!$getLock){
return response()->json(json_decode(Response::setError("请勿重复请求,请5秒后再发起请求"), true));
}
// $result = Redis::Connection("wms")->set('wms_' . $key, 1,"EX",5,"NX");
// if(!$result){
// throw new InvalidRequestException("请勿重复请求,请5秒后再发起请求");
// }
$response = $next($request);
WmsLockService::delLock($key);
// Redis::Connection("wms")->del('wms_' . $key);
return $response;
}
}
WmsLockService.php
<?php
namespace App\Http\Services;
use Illuminate\Support\Facades\Redis;
class WmsLockService
{
const LOCK_KEY = "wms_lock_";
public static function getLock($Key="",$time=15){
$requestId = uniqid(); // 生成一个唯一的请求ID
$expireTime = 1000 * intval($time); // 锁的过期时间,单位毫秒
// Lua脚本
$luaScript = <<eval($luaScript, 1, $lockKey, $requestId, $expireTime);
return $result;
}
public static function delLock($lockKey=""){
Redis::Connection("wms")->del(self::LOCK_KEY.$lockKey);
}
}
路由
Route::match(['get', 'post'], '/stockIn/stockShelf/oneKeyPutawayAction', 'StockShelfController@oneKeyPutawayAction')->middleware('prevent_dup_submit')
中间件
2,假如业务中出现非重复点击,或者由于事务中处理比较慢(请求上架或者理货 请求参数类似于[1,3,5] [1,3,8,9]),两次请求中都有请求参数id:1,3 会造成1和3的并发问题。
处理方法就是针对具体请求的函数对单个参数进行加锁 当上架id:[1,3,5]请求的时候可以让1,3,5分别进行加锁,下一个1,3,8,9来请求的时候就会因为拿不到锁而报错
RedisLock
systemName = $systemName;
$this->functionName = $functionName;
}
public static function initInstance($systemName, $functionName)
{
return new self($systemName, $functionName);
}
public function lock($key, $ttl = null)
{
$redis = Redis::connection();
$randNum = mt_rand(10000000, 99999999);
$ttl = $ttl ?? self::TTL;
$redisKey = self::KEY_PREFIX . ":{$this->systemName}:{$this->functionName}:{$key}";
$result = $redis->setNx($redisKey, $randNum);
if ($result) {
$redis->expire($redisKey, $ttl);
$this->randNumMap[$key] = $randNum;
return $randNum;
} else {
return null;
}
}
public function unlock($key, $randNum)
{
$redis = Redis::connection();
$redisKey = self::KEY_PREFIX . ":{$this->systemName}:{$this->functionName}:{$key}";
$lua = <<eval($lua, 1, $redisKey, $randNum);
return $result;
}
public function lockFunction($key, callable $callback,callable $failCallback = null)
{
$random = $this->lock($key);
if ($random !== null) {
$result = call_user_func($callback);
$delResult = $this->unlock($key, $random);
if ($delResult==0){
if ($failCallback){
call_user_func($failCallback);
}
}
return $result;
} else {
return false;
}
}
public function lockBatchKey($keyArr, $ttl = null)
{
$lockResult = [];
foreach ($keyArr as $key) {
$result = $this->lock($key, $ttl);
if ($result) {
$lockResult[$key] = $result;
} else {
$lockResult[$key] = 0;
}
}
return $lockResult;
}
public function unlockBatchKey($resultArr)
{
$unlockResult = [];
foreach ($resultArr as $key => $random) {
$random = $this->randNumMap[$key] ?? $random;
$result = $this->unlock($key, $random);
if ($result) {
$unlockResult[$key] = true;
} else {
$unlockResult[$key] = false;
}
}
return $unlockResult;
}
}
在开发过程中刚开始使用的是上述第一种方法,但是偶尔3-6个月会出现一次重复数据,目前没有找到具体原因,所以后来又采用第二种更加细粒度的加锁方式,对请求的具体参数进行加锁,希望能帮到大家解决开发过程中遇到类似的问题提供解决思路