thinkphp设置redis分布式锁

1.设置redis为缓存驱动

// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------

return [
// 驱动方式
'type' => 'redis',
// 服务器地址
'host' => '127.0.0.1',
'port' => 6379,
'password' => env('redis.password', ''),
'select' => 0,
//缓存有效期 0表示永久缓存
'expire' => 3600*72,
'prefix' => '',
'timeout' => 3600,
];

 

2.引入

use think\facade\Cache;


3.使用:
// 防止重复提交
$orderLockKey = 'user_recharge_lock:' . $this->uid;
if (Cache::has($orderLockKey)) {
return json(['code' => 0, 'msg' => '请勿重复发送']);
}

4.异常时需主动销毁:
Cache::delete($orderLockKey);

案例代码如下

 

image

 

posted @ 2025-11-18 12:11  幽暗天琴  阅读(10)  评论(0)    收藏  举报