1. 程式人生 > 實用技巧 >鎖機制處理類

鎖機制處理類

<?php


namespace app\common\library;

use think\Cache;
use think\Exception;

/**
 * 鎖機制
 */
class Lock
{

    public function run($callback, $key, $expire = 10)
    {
        try {
            if (Cache::store('redis')->has($key)) {
                throw new LockException('已鎖定');
            }
            Cache
::store('redis')->set($key, 1, $expire); $result = null; if (is_callable($callback)) { $result = call_user_func_array($callback, [$this]); } return $result; } catch (LockException $e) { throw $e; } catch (\Exception
$e) { Cache::store('redis')->rm($key); throw $e; } catch (\Throwable $e) { Cache::store('redis')->rm($key); throw $e; } } } class LockException extends Exception{ }

呼叫:

  try {
       $result = (new Lock)->run(function
() use () {   // code   return true;   } }, $key, 10); } catch (Exception $e) { return false; }