찾다
백엔드 개발PHP 튜토리얼PHP 동시 잠금 사례 분석

PHP 동시 잠금 사례 분석

May 31, 2018 pm 04:19 PM
php잠그다사례 연구

이 글에서는 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP 세션에 어떤 데이터를 저장할 수 있습니까?PHP 세션에 어떤 데이터를 저장할 수 있습니까?May 02, 2025 am 12:17 AM

phpsessionscanstorestrings, 숫자, 배열 및 객체 1.Strings : TextDatalikeUsernames.2.numbers : integorfloatsforcounters.3.arrays : listslikeshoppingcarts.4.objects : complexStructuresThatareserialized.

PHP 세션을 어떻게 시작합니까?PHP 세션을 어떻게 시작합니까?May 02, 2025 am 12:16 AM

tostartAphPessession, us

세션 재생이란 무엇이며 보안을 어떻게 개선합니까?세션 재생이란 무엇이며 보안을 어떻게 개선합니까?May 02, 2025 am 12:15 AM

세션 재생은 세션 고정 공격의 경우 사용자가 민감한 작업을 수행 할 때 새 세션 ID를 생성하고 이전 ID를 무효화하는 것을 말합니다. 구현 단계에는 다음이 포함됩니다. 1. 민감한 작업 감지, 2. 새 세션 ID 생성, 3. 오래된 세션 ID 파괴, 4. 사용자 측 세션 정보 업데이트.

PHP 세션을 사용할 때 몇 가지 성능 고려 사항은 무엇입니까?PHP 세션을 사용할 때 몇 가지 성능 고려 사항은 무엇입니까?May 02, 2025 am 12:11 AM

PHP 세션은 응용 프로그램 성능에 큰 영향을 미칩니다. 최적화 방법은 다음과 같습니다. 1. 데이터베이스를 사용하여 세션 데이터를 저장하여 응답 속도를 향상시킵니다. 2. 세션 데이터 사용을 줄이고 필요한 정보 만 저장하십시오. 3. 비 차단 세션 프로세서를 사용하여 동시성 기능을 향상시킵니다. 4. 사용자 경험과 서버 부담의 균형을 맞추기 위해 세션 만료 시간을 조정하십시오. 5. 영구 세션을 사용하여 데이터 읽기 및 쓰기 시간의 수를 줄입니다.

PHP 세션은 쿠키와 어떻게 다릅니 까?PHP 세션은 쿠키와 어떻게 다릅니 까?May 02, 2025 am 12:03 AM

phpsessionsareser-side, whilecookiesareclient-side.1) sessions stessoredataontheserver, andhandlargerdata.2) cookiesstoredataonthecure, andlimitedinsize.usesessionsforsensitivestataondcookiesfornon-sensistive, client-sensation.

PHP는 사용자 세션을 어떻게 식별합니까?PHP는 사용자 세션을 어떻게 식별합니까?May 01, 2025 am 12:23 AM

phpidifiesauser의 sssessionusessessioncookiesandssessionids.1) whensession_start () iscalled, phpgeneratesauniquessessionStoredInacookienamedPhpsSessIdonSeuser 'sbrowser.2) thisidallowsphptoretrievessessionDataTromServer.

PHP 세션을 확보하기위한 모범 사례는 무엇입니까?PHP 세션을 확보하기위한 모범 사례는 무엇입니까?May 01, 2025 am 12:22 AM

PHP 세션의 보안은 다음 측정을 통해 달성 할 수 있습니다. 1. Session_REGENEREAT_ID ()를 사용하여 사용자가 로그인하거나 중요한 작업 일 때 세션 ID를 재생합니다. 2. HTTPS 프로토콜을 통해 전송 세션 ID를 암호화합니다. 3. 세션 _save_path ()를 사용하여 세션 데이터를 저장하고 권한을 올바르게 설정할 보안 디렉토리를 지정하십시오.

PHP 세션 파일은 기본적으로 어디에 저장됩니까?PHP 세션 파일은 기본적으로 어디에 저장됩니까?May 01, 2025 am 12:15 AM

phpsessionfilesarestoredInTheRectorySpecifiedBysession.save_path, 일반적으로/tmponunix-likesystemsorc : \ windows \ temponwindows.tocustomizethis : 1) austession_save_path () toSetacustomDirectory, verlyTeCustory-swritation;

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!