찾다
백엔드 개발PHP 튜토리얼PHP로 구현된 memcached 대기열 클래스

  1. /*
  2. * memcache 대기열 클래스
  3. * 여러 프로세스에 의한 동시 쓰기 및 읽기 지원
  4. * 쓰는 동안 읽기, AB 문자 회전 교체
  5. * @author guoyu
  6. * @create on 9:25 2014-9-28
  7. * @qq 기술산업 교류회 : 136112330
  8. *
  9. * @예:
  10. * $obj = new memcacheQueue('duilie');
  11. * $obj->add('1asdf')
  12. * $obj->getQueueLength(); read(11); * $obj->get(8);
  13. */
  14. class memcacheQueue{
  15. public static $client
  16. public $access; //큐 업데이트 가능 여부
  17. private $currentSide; //현재 회전의 큐 쪽: A/B
  18. private $lastSide; //이전 회전의 큐 쪽: A/ B
  19. private $sideAHead; //A측의 첫 번째 값
  20. private $sideATail; //A측의 마지막 값
  21. private $sideBHead; //B측의 첫 번째 값
  22. private $sideBTail; // B팀의 마지막 값
  23. private $currentHead; //현재 팀의 첫 번째 값
  24. private $currentTail; //현재 팀의 마지막 값
  25. private $lastHead; > private $ lastTail; //팀의 마지막 라운드의 꼬리 값
  26. private $expire; //만료 시간, 초, 1~2592000, 즉 30일 이내에는 만료되지 않음을 의미합니다.
  27. private $ sleepTime; //잠금 해제 대기 시간, 마이크로초
  28. private $queueName; //큐 이름, 고유 값
  29. private $retryNum; //재시도 횟수, = 10 * 이론적인 동시성 수
  30. const MAXNUM = 2000; //(단면) 최대 대기열 수, 권장 상한은 10K입니다.
  31. const HEAD_KEY = '_lkkQueueHead_' // 대기열 헤드 키
  32. const TAIL_KEY = '_lkkQueueTail_' // 대기열 꼬리 키
  33. const VALU_KEY = '_lkkQueueValu_'; // 대기열 값 키
  34. const LOCK_KEY = '_lkkQueueLock_' // 대기열 잠금 키
  35. const SIDE_KEY = '_lkkQueueSide_' // 회전 표면 키
  36. /*
  37. * 생성자
  38. * @param [config] 배열 memcache 서버 매개변수
  39. * @param [queueName] 문자열 대기열 이름
  40. * @param [expire] 문자열 만료 시간
  41. * @return NULL
  42. */
  43. 공용 함수 __construct($queueName ='',$expire='',$config =''){
  44. if(empty($config)){
  45. self::$client = memcache_pconnect('localhost',11211 );
  46. }elseif(is_array($config)){//array('host'=>'127.0.0.1','port'=> ;'11211')
  47. self::$client = memcache_pconnect($config['host'],$config['port'])
  48. }elseif(is_string($config)){//"127.0 .0.1:11211"
  49. $tmp = 폭발(' :',$config);
  50. $conf['host'] = isset($tmp[0]) ? $tmp[0] : '127.0. 0.1';
  51. $conf['port'] = isset($tmp[1]) ? $tmp[1] : '11211'
  52. self::$client($conf['host') ],$conf['port']);
  53. }
  54. if(!self::$client) return false
  55. ignore_user_abort(TRUE);//클라이언트 연결이 끊어지면 실행을 허용합니다. 계속
  56. set_time_limit(0);//스크립트 실행 지연 상한
  57. $this->access = false
  58. $this->sleepTime = 1000; = (비어 있음($expire) && $expire!=0) ? 3600 : (int)$expire;
  59. $this->expire = $expire; 🎜> $this->retryNum = 10000;
  60. $side = memcache_add(self::$client, $queueName . self::SIDE_KEY, 'A',false, $expire)
  61. $ this->getHeadNTail($queueName);
  62. if (!isset($this->sideAHead) || 비어 있음($this->sideAHead)) $this->sideAHead = 0; (!isset($this->sideATail) || 비어 있음 ($this->sideATail)) $this->sideATail = 0
  63. if(!isset($this->sideBHead) || 비어 있음 ($this->sideBHead)) $this-> sideBHead = 0
  64. if(!isset($this->sideBHead) || 비어 있음($this->sideBHead)) $this-> sideBHead = 0
  65. }
  66. /*
  67. * 获取队列首尾值
  68. * @param [queueName] string 队列name称
  69. * @return NULL
  70. */
  71. 비공개 함수 getHeadNTail($queueName) {
  72. $this->sideAHead = (int)memcache_get(self::$client, $queueName.'A'.self::HEAD_KEY);
  73. $this->sideATail = (int)memcache_get(self::$client, $queueName.'A'.self::TAIL_KEY);
  74. $this->sideBHead = (int)memcache_get(self::$client, $queueName.'B'.self::HEAD_KEY);
  75. $this->sideBTail = (int)memcache_get(self::$client, $queueName.'B'.self::TAIL_KEY);
  76. }
  77. /*
  78. * 获取当前轮值的队列면
  79. * @return string 队列면명称
  80. */
  81. 공용 함수 getCurrentSide(){
  82. $ currentSide = memcache_get(self::$client, $this->queueName . self::SIDE_KEY);
  83. if($currentSide == 'A'){
  84. $this->currentSide = 'A';
  85. $this->lastSide = 'B';
  86. $this->currentHead = $this->sideAHead;
  87. $this->currentTail = $this->sideATail;
  88. $this->lastHead = $this->sideBHead;
  89. $this->lastTail = $this->sideBTail;
  90. }else{
  91. $this->currentSide = 'B';
  92. $this->lastSide = 'A';
  93. $this->currentHead = $this->sideBHead;
  94. $this->currentTail = $this->sideBTail;
  95. $this->lastHead = $this->sideAHead;
  96. $this->lastTail = $this->sideATail;
  97. }
  98. return $this->currentSide;
  99. }
  100. /*
  101. * 队列加锁
  102. * @return boolean
  103. */
  104. 비공개 함수 getLock(){
  105. if($this-> access === false){
  106. while(!memcache_add(self::$client, $this->queueName .self::LOCK_KEY, 1, false, $this->expire) ){
  107. usleep ($this->sleepTime);
  108. @$i ;
  109. if($i > $this->retryNum){//尝试等待N次
  110. return false;
  111. 휴식;
  112. }
  113. }
  114. return $this->access = true;
  115. }
  116. false를 반환합니다.
  117. }
  118. /*
  119. * 队列解锁
  120. * @return NULL
  121. */
  122. 비공개 함수 unLock(){
  123. memcache_delete(self::$client, $this->queueName .self::LOCK_KEY);
  124. $this->access = false;
  125. }
  126. /*
  127. * 添加数据
  128. * @param [data] 要存储的值
  129. * @return boolean
  130. */
  131. 공용 함수 add( $data){
  132. $result = false;
  133. if(!$this->getLock()){
  134. return $result;
  135. }
  136. $this->getHeadNTail($this->queueName);
  137. $this->getCurrentSide();
  138. if($this->isFull()){
  139. $this->unLock();
  140. false를 반환합니다.
  141. }
  142. if($this->currentTail $value_key = $this->queueName .$this->currentSide . 자기::VALU_KEY . $this->currentTail;
  143. if(memcache_add(self::$client, $value_key, $data, false, $this->expire)){
  144. $this->changeTail();
  145. $결과 = 참;
  146. }
  147. }else{//当前队列已满,更换轮值面
  148. $this->unLock();
  149. $this->changeCurrentSide();
  150. return $this->add($data);
  151. }
  152. $this->unLock();
  153. $결과 반환;
  154. }
  155. /*
  156. * 取出数据
  157. * @param [length] int 数据的长titude
  158. * @return 배열
  159. */
  160. 공용 함수 get( $length=0){
  161. if(!is_numeric($length)) return false;
  162. if(empty($length)) $length = self::MAXNUM * 2;//默认读取所有
  163. if(!$this->getLock()) return false;
  164. if($this->isEmpty()){
  165. $this->unLock();
  166. false를 반환합니다.
  167. }
  168. $keyArray = $this->getKeyArray($length);
  169. $lastKey = $keyArray['lastKey'];
  170. $currentKey = $keyArray['currentKey'];
  171. $keys = $keyArray['keys'];
  172. $this->changeHead($this->lastSide,$lastKey);
  173. $this->changeHead($this->currentSide,$currentKey);
  174. $data = @memcache_get(self::$client, $keys);
  175. foreach($keys as $v){//출지后删除
  176. @memcache_delete(self::$client, $v, 0);
  177. }
  178. $this->unLock();
  179. $data를 반환합니다.
  180. }
  181. /*
  182. * 读取数据
  183. * @param [length] int 数据的长島
  184. * @return 배열
  185. */
  186. 공용 함수 읽기 ($length=0){
  187. if(!is_numeric($length)) return false;
  188. if(empty($length)) $length = self::MAXNUM * 2;//默认读取所有
  189. $keyArray = $this->getKeyArray($length);
  190. $data = @memcache_get(self::$client, $keyArray['keys']);
  191. $data를 반환합니다.
  192. }
  193. /*
  194. * 获取队列某段长島的key数组
  195. * @param [length] int 队列长島
  196. * @return 배열
  197. */
  198. 개인 함수 getKeyArray($length){
  199. $result = array('keys'=>array(),'lastKey'=>array(),'currentKey'=>array());
  200. $this->getHeadNTail($this->queueName);
  201. $this->getCurrentSide();
  202. if(empty($length)) return $result;
  203. //상위 키
  204. $i = $result['lastKey'] = 0;
  205. for($i=0;$i $result['lastKey'] = $this->lastHead $i;
  206. if($result['lastKey'] >= $this->lastTail) break;
  207. $result['keys'][] = $this->queueName .$this->lastSide . 자기::VALU_KEY . $result['lastKey'];
  208. }
  209. //再取当앞면의 키
  210. $j = $length - $i;
  211. $k = $result['currentKey'] = 0;
  212. for($k=0;$k $result['currentKey'] = $this->currentHead $k;
  213. if($result['currentKey'] >= $this->currentTail) break;
  214. $result['keys'][] = $this->queueName .$this->currentSide . 자기::VALU_KEY . $result['현재키'];
  215. }
  216. $result 반환;
  217. }
  218. /*
  219. * 更新当前轮值면队列尾적值
  220. * @return NULL
  221. */
  222. 비공개 함수changeTail(){
  223. $tail_key = $this->queueName .$this->currentSide . 자기::TAIL_KEY;
  224. memcache_add(self::$client, $tail_key, 0,false, $this->expire);//如果没有,则插入;有则false;
  225. //memcache_increment(self::$client, $tail_key, 1);//队列尾 1
  226. $v = memcache_get(self::$client, $tail_key) 1;
  227. memcache_set(self::$client, $tail_key,$v,false,$this->expire);
  228. }
  229. /*
  230. * 更新队列首적值
  231. * @param [side] string 要更新的面
  232. * @param [headValue] int 队列首的值
  233. * @return NULL
  234. */
  235. 비공개 함수changeHead($side,$headValue){
  236. if($headValue $head_key = $this->queueName .$side . 자기::HEAD_KEY;
  237. $tail_key = $this->queueName .$side . 자기::TAIL_KEY;
  238. $sideTail = memcache_get(self::$client, $tail_key);
  239. if($headValue memcache_set(self::$client, $head_key,$headValue 1,false,$this->expire);
  240. }elseif($headValue >= $sideTail){
  241. $this->resetSide($side);
  242. }
  243. }
  244. /*
  245. * 큼 거대한 화면
  246. * @return NULL
  247. */
  248. 개인 함수 ResetSide($side){
  249. $head_key = $this->queueName .$side . 자기::HEAD_KEY;
  250. $tail_key = $this->queueName .$side . 자기::TAIL_KEY;
  251. memcache_set(self::$client, $head_key,0,false,$this->expire);
  252. memcache_set(self::$client, $tail_key,0,false,$this->expire);
  253. }
  254. /*
  255. * 改变当前轮值队列면
  256. * @return string
  257. */
  258. private functionchangeCurrentSide(){
  259. $currentSide = memcache_get(self::$ 클라이언트, $this->queueName .self::SIDE_KEY);
  260. if($currentSide == 'A'){
  261. memcache_set(self::$client, $this->queueName . self::SIDE_KEY,'B',false,$this->expire) ;
  262. $this->currentSide = 'B';
  263. }else{
  264. memcache_set(self::$client, $this->queueName . self::SIDE_KEY,'A',false,$this->expire);
  265. $this->currentSide = 'A';
  266. }
  267. return $this->currentSide;
  268. }
  269. /*
  270. * 检查当前队列是否已满
  271. * @return boolean
  272. */
  273. public function isFull(){
  274. $result = false ;
  275. if($this->sideATail == self::MAXNUM && $this->sideBTail == self::MAXNUM){
  276. $result = true;
  277. }
  278. $result 반환;
  279. }
  280. /*
  281. * 检查当前队列是否为空
  282. * @return boolean
  283. */
  284. public function isEmpty(){
  285. $result = true ;
  286. if($this->sideATail > 0 || $this->sideBTail > 0){
  287. $result = false;
  288. }
  289. $result 반환;
  290. }
  291. /*
  292. * 获取当前队列적 속도
  293. * 该长島为理论长島,某些元素由于过期失效而丢失,真实속도 小于或等于该长島
  294. * @return int
  295. */
  296. 공용 함수 getQueueLength(){
  297. $this->getHeadNTail($this->queueName);
  298. $this->getCurrentSide();
  299. $sideALength = $this->sideATail - $this->sideAHead;
  300. $sideBLength = $this->sideBTail - $this->sideBHead;
  301. $result = $sideALength $sideBLength;
  302. $result를 반환합니다.
  303. }
  304. /*
  305. * 清空当前队列数据,仅保留HEAD_KEY、TAIL_KEY、SIDE_KEY삼키key
  306. * @return boolean
  307. */
  308. 공개 함수 클리어( ){
  309. if(!$this->getLock()) return false;
  310. for($i=0;$i<:maxnum> @memcache_delete(self::$client, $this->queueName.'A'.self::VALU_KEY . $i, 0);
  311. @memcache_delete(self::$client, $this->queueName.'B'.self::VALU_KEY .$i, 0);
  312. }
  313. $this->unLock();
  314. $this->resetSide('A');
  315. $this->resetSide('B');
  316. true를 반환합니다.
  317. }
  318. /*
  319. * 清除所有memcache缓存数据
  320. * @return NULL
  321. */
  322. 공용 함수 memFlush(){
  323. memcache_flush(self:: $클라이언트);
  324. }
  325. }
复제대码

PHP, 멤캐시


성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개Instagram API 소개Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다Laravel의 플래시 세션 데이터로 작업합니다Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축Laravel Back End : Part 2, React가있는 React 앱 구축Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱Laravel 테스트에서 단순화 된 HTTP 응답 조롱Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP 상황 조사 발표2025 PHP 상황 조사 발표Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

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

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경