>  기사  >  백엔드 개발  >  PHP에서 동시성을 잠그는 방법에 대한 예제 코드

PHP에서 동시성을 잠그는 방법에 대한 예제 코드

黄舟
黄舟원래의
2017-07-17 15:50:162312검색

CleverCode의 작업 프로젝트에서는 데이터를 수정하기 위해 일부 PHP 동시 액세스 문제가 발생합니다. 데이터가 잠겨 있지 않으면 데이터 오류가 발생합니다. 다음 CleverCode에서는 금융 결제 잠금 문제를 분석합니다.

1 애플리케이션 잠금 메커니즘 없음

1.1 금융결제 단순화 버전 코드

<?php

/** 
 * pay.php 
 * 
 * 支付没有应用锁
 * 
 * Copy right (c) 2016 http://blog.csdn.net/CleverCode 
 * 
 * modification history: 
 * -------------------- 
 * 2016/9/10, by CleverCode, Create 
 * 
 */  

//用户支付
function pay($userId,$money)
{
    
    if(false == is_int($userId) || false == is_int($money))
    {
        return false;
    }  
    
    //取出总额
    $total = getUserLeftMoney($userId);
    
    //花费大于剩余
    if($money > $total)
    {
        return false;    
    }
    
    //余额
    $left = $total - $money;
    
    //更新余额
    return setUserLeftMoney($userId,$left);

}

//取出用户的余额
function getUserLeftMoney($userId)
{
    if(false == is_int($userId))
    {
        return 0;
    }
    $sql = "select account form user_account where userid = ${userId}";
    
    //$mysql = new mysql();//mysql数据库
    return $mysql->query($sql);
}

//更新用户余额
function setUserLeftMoney($userId,$money)
{
    if(false == is_int($userId) || false == is_int($money))
    {
        return false;
    }        
    
    $sql = "update user_account set account = ${money} where userid = ${userId}";
    
    //$mysql = new mysql();//mysql数据库
    return $mysql->execute($sql);
}

?>

1.2 문제 분석

사업자가 2명(p,m)인 경우 PC와 로그는 각각 사용자번호 100번 계정을 사용합니다. 동시에 휴대폰에 로그인하면 100 계좌의 총 잔액은 1000이고, p 운영자는 200, m 운영자는 300을 지출합니다. 동시 진행 과정은 다음과 같습니다.

p 운영자:

1 사용자의 잔액 1000을 빼냅니다.

2 결제 후 남은 금액은 800 = 1000 - 200 입니다.

3 업데이트된 계정 잔액은 800입니다.

m 운영자:

1 사용자의 잔액 1000을 출금합니다.

결제 후 남은 2 700 = 1000 - 300.

3 결제 후 계좌 잔액은 700입니다.

두 번 결제한 후에도 계정 잔액은 여전히 ​​700입니다. 500을 지출한 후에도 계정 잔액은 500이어야 합니다. 이러한 현상의 근본 원인은 동시성 시 p와 m이 동시에 얻은 잔액 데이터가 모두 1000이기 때문입니다.

2 잠금 설계

잠금 작업에는 일반적으로 두 단계만 있습니다. 하나는 잠금을 획득하는 것이고(getLock), 다른 하나는 잠금을 해제하는 것입니다(releaseLock). 그러나 파일 구현, Memcache 구현 등 실제로 잠금을 구현하는 방법은 다양합니다.

2.1 클래스 다이어그램은 다음과 같이 설계되었습니다


2.2 PHP 소스 코드는 다음과 같이 설계되었습니다

LockSystem.php

<?php

/** 
 * LockSystem.php 
 * 
 * php锁机制
 * 
 * Copy right (c) 2016 http://blog.csdn.net/CleverCode 
 * 
 * modification history: 
 * -------------------- 
 * 2016/9/10, by CleverCode, Create 
 * 
 */ 

class LockSystem
{
    const LOCK_TYPE_DB = &#39;SQLLock&#39;;
    const LOCK_TYPE_FILE = &#39;FileLock&#39;;
    const LOCK_TYPE_MEMCACHE = &#39;MemcacheLock&#39;;
    
    private $_lock = null;
    private static $_supportLocks = array(&#39;FileLock&#39;, &#39;SQLLock&#39;, &#39;MemcacheLock&#39;);  
    
    public function construct($type, $options = array()) 
    {
        if(false == empty($type))
        {
            $this->createLock($type, $options);
        }
    }   

    public function createLock($type, $options=array())
    {
        if (false == in_array($type, self::$_supportLocks))
        {
            throw new Exception("not support lock of ${type}");
        }
        $this->_lock = new $type($options);
    }
    
    public function getLock($key, $timeout = ILock::EXPIRE)
    {
        if (false == $this->_lock instanceof ILock)  
        {
            throw new Exception(&#39;false == $this->_lock instanceof ILock&#39;);          
        }  
        $this->_lock->getLock($key, $timeout);   
    }
    
    public function releaseLock($key)
    {
        if (false == $this->_lock instanceof ILock)  
        {
            throw new Exception(&#39;false == $this->_lock instanceof ILock&#39;);          
        }  
        $this->_lock->releaseLock($key);         
    }   
}

interface ILock
{
    const EXPIRE = 5;
    public function getLock($key, $timeout=self::EXPIRE);
    public function releaseLock($key);
}

class FileLock implements ILock
{
    private $_fp;
    private $_single;

    public function construct($options)
    {
        if (isset($options[&#39;path&#39;]) && is_dir($options[&#39;path&#39;]))
        {
            $this->_lockPath = $options[&#39;path&#39;].&#39;/&#39;;
        }
        else
        {
            $this->_lockPath = &#39;/tmp/&#39;;
        }
       
        $this->_single = isset($options[&#39;single&#39;])?$options[&#39;single&#39;]:false;
    }

    public function getLock($key, $timeout=self::EXPIRE)
    {
        $startTime = Timer::getTimeStamp();

        $file = md5(FILE.$key);
        $this->fp = fopen($this->_lockPath.$file.&#39;.lock&#39;, "w+");
        if (true || $this->_single)
        {
            $op = LOCK_EX + LOCK_NB;
        }
        else
        {
            $op = LOCK_EX;
        }
        if (false == flock($this->fp, $op, $a))
        {
            throw new Exception(&#39;failed&#39;);
        }
       
	    return true;
    }

    public function releaseLock($key)
    {
        flock($this->fp, LOCK_UN);
        fclose($this->fp);
    }
}

class SQLLock implements ILock
{
    public function construct($options)
    {
        $this->_db = new mysql(); 
    }

    public function getLock($key, $timeout=self::EXPIRE)
    {       
        $sql = "SELECT GET_LOCK(&#39;".$key."&#39;, &#39;".$timeout."&#39;)";
        $res =  $this->_db->query($sql);
        return $res;
    }

    public function releaseLock($key)
    {
        $sql = "SELECT RELEASE_LOCK(&#39;".$key."&#39;)";
        return $this->_db->query($sql);
    }
}

class MemcacheLock implements ILock
{
    public function construct($options)
    {
        
        $this->memcache = new Memcache();
    }

    public function getLock($key, $timeout=self::EXPIRE)
    {     
        $waitime = 20000;
        $totalWaitime = 0;
        $time = $timeout*1000000;
        while ($totalWaitime < $time && false == $this->memcache->add($key, 1, $timeout)) 
        {
            usleep($waitime);
            $totalWaitime += $waitime;
        }
        if ($totalWaitime >= $time)
            throw new Exception(&#39;can not get lock for waiting &#39;.$timeout.&#39;s.&#39;);

    }

    public function releaseLock($key)
    {
        $this->memcache->delete($key);
    }
}

3 애플리케이션 잠금 메커니즘

3.1 결제 시스템 애플리케이션 잠금

<?php

/** 
 * pay.php 
 * 
 * 支付应用锁
 * 
 * Copy right (c) 2016 http://blog.csdn.net/CleverCode 
 * 
 * modification history: 
 * -------------------- 
 * 2016/9/10, by CleverCode, Create 
 * 
 */  

//用户支付
function pay($userId,$money)
{
    
    if(false == is_int($userId) || false == is_int($money))
    {
        return false;
    }  
    
    try
    {
        //创建锁(推荐使用MemcacheLock)
        $lockSystem = new LockSystem(LockSystem::LOCK_TYPE_MEMCACHE);             
        
        //获取锁
        $lockKey = &#39;pay&#39;.$userId;
        $lockSystem->getLock($lockKey,8);
        
        //取出总额
        $total = getUserLeftMoney($userId);
        
        //花费大于剩余
        if($money > $total)
        {
            $ret = false;    
        }
        else
        { 
            //余额
            $left = $total - $money;
            
            //更新余额
            $ret = setUserLeftMoney($userId,$left);
        }
        
        //释放锁
        $lockSystem->releaseLock($lockKey); 
    }
    catch (Exception $e)
    {
        //释放锁
        $lockSystem->releaseLock($lockKey);     
    }

}

//取出用户的余额
function getUserLeftMoney($userId)
{
    if(false == is_int($userId))
    {
        return 0;
    }
    $sql = "select account form user_account where userid = ${userId}";
    
    //$mysql = new mysql();//mysql数据库
    return $mysql->query($sql);
}

//更新用户余额
function setUserLeftMoney($userId,$money)
{
    if(false == is_int($userId) || false == is_int($money))
    {
        return false;
    }        
    
    $sql = "update user_account set account = ${money} where userid = ${userId}";
    
    //$mysql = new mysql();//mysql数据库
    return $mysql->execute($sql);
}

?>

3.2 잠금 분석

p 운영자:

1 잠금 받기: pay100

2 사용자 잔액 1000을 출금합니다.

3 결제 후 남은 금액은 800 = 1000 - 200 입니다.

4 업데이트된 계정 잔액은 800입니다.

5 잠금 해제: pay100

운영자:

1 잠금 대기: pay100

2 잠금 받기: pay100

3 잔액 받기: 800

4 결제 후 남은 500 = 800 - 300.

5 결제 후 계좌 잔액은 500입니다.

6 잠금 해제: pay100

두 번 결제하면 잔액은 500입니다. 동시성으로 인해 발생하는 크리티컬 섹션 리소스의 접근 문제를 완벽하게 해결합니다.

위 내용은 PHP에서 동시성을 잠그는 방법에 대한 예제 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.