PHP 동시 잠금 사례 분석

墨辰丷
풀어 주다: 2023-03-28 18:20:01
원래의
2028명이 탐색했습니다.

이 글에서는 PHP 동시 잠금의 예를 소개합니다. 데이터는 한 번에 한 명의 사용자만 조작할 수 있습니다. 이때 잠금이 필요한 친구는 자세히 알아볼 수 있습니다.

작업 프로젝트에서 데이터를 수정하기 위해 PHP에 동시 액세스하는 데 몇 가지 문제가 발생합니다. 데이터가 잠겨 있지 않으면 데이터 오류가 발생합니다. 아래에서는 금융결제 잠금 문제를 분석하겠습니다. 그것이 모두에게 도움이 되기를 바랍니다.

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

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

<!--?php 
/** 
 * pay.php 
 * 
 * 支付没有应用锁
 * 
 * Copy right (c) 2016 
 * 
 * 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 문제 분석

두 명의 연산자(p 및 m)가 있는 경우 둘 다 사용 사용자 번호 100의 계정과 PC 및 휴대폰에서 각각 로그인하면 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). 그러나 실제로 잠금을 구현하는 방법은 파일 구현, SQL 구현, Memcache 구현 등 여러 가지가 있습니다. 이 시나리오에서는 전략 모드 사용을 고려합니다.

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

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

LockSystem.php

<!--?php 
/** 
 * LockSystem.php 
 * 
 * php锁机制
 * 
 * Copy right (c) 2016
 * 
 * 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 
 * 
 * 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

m 운영자:

  1. 잠금 대기 중: pay100

  2. 잠금 받기: pay100

  3. 잔액 가져오기: 800

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

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

  6. 해제 잠금: pay100

2회 결제 후 잔액은 500입니다. 동시성으로 인해 발생하는 임계 영역 리소스의 접근 문제를 완벽하게 해결합니다.

요약: 위 내용이 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

관련 권장사항:

PHP는 file_get_contents를 사용하여 간단한 함수로 http 요청을 보냅니다

PHP+MySQL 높은 동시성 잠금 트랜잭션 처리 문제 해결

PHP로 구현된 Monkey King 알고리즘(원숭이가 왕을 선택합니다) )

위 내용은 PHP 동시 잠금 사례 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!