1. 程式人生 > 資料庫 >使用redis限制提交次數

使用redis限制提交次數

public function somthing($user_id)
{
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    
    // 鎖不存在,就執行業務程式碼
    if (!$redis->exists("lock:{$user_id}")) {
    
        // ==========
        // do somthing
        // ==========

        // 在 Redis 中存一個有效期60秒的快取鎖
        $redis->set('lock:{$user_id}', 1, 60);
        
        return ['msg' => 1, 'message' => '操作成功', 'data' => 'somthing'];
    }

    return ['msg' => 0, 'message' => '每分鐘只允許呼叫一次'];
}