찾다
백엔드 개발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으로 문의하세요.
PHP vs. Python : 차이점 이해PHP vs. Python : 차이점 이해Apr 11, 2025 am 12:15 AM

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP : 죽어 가거나 단순히 적응하고 있습니까?PHP : 죽어 가거나 단순히 적응하고 있습니까?Apr 11, 2025 am 12:13 AM

PHP는 죽지 않고 끊임없이 적응하고 진화합니다. 1) PHP는 1994 년부터 새로운 기술 트렌드에 적응하기 위해 여러 버전 반복을 겪었습니다. 2) 현재 전자 상거래, 컨텐츠 관리 시스템 및 기타 분야에서 널리 사용됩니다. 3) PHP8은 성능과 현대화를 개선하기 위해 JIT 컴파일러 및 기타 기능을 소개합니다. 4) Opcache를 사용하고 PSR-12 표준을 따라 성능 및 코드 품질을 최적화하십시오.

PHP의 미래 : 적응 및 혁신PHP의 미래 : 적응 및 혁신Apr 11, 2025 am 12:01 AM

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.

PHP의 초록 클래스 또는 인터페이스에 대한 특성과 언제 특성을 사용 하시겠습니까?PHP의 초록 클래스 또는 인터페이스에 대한 특성과 언제 특성을 사용 하시겠습니까?Apr 10, 2025 am 09:39 AM

PHP에서, 특성은 방법 재사용이 필요하지만 상속에 적합하지 않은 상황에 적합합니다. 1) 특성은 클래스에서 다중 상속의 복잡성을 피할 수 있도록 수많은 방법을 허용합니다. 2) 특성을 사용할 때는 대안과 키워드를 통해 해결할 수있는 방법 충돌에주의를 기울여야합니다. 3) 성능을 최적화하고 코드 유지 보수성을 향상시키기 위해 특성을 과도하게 사용해야하며 단일 책임을 유지해야합니다.

DIC (Dependency Injection Container) 란 무엇이며 PHP에서 사용하는 이유는 무엇입니까?DIC (Dependency Injection Container) 란 무엇이며 PHP에서 사용하는 이유는 무엇입니까?Apr 10, 2025 am 09:38 AM

의존성 주입 컨테이너 (DIC)는 PHP 프로젝트에 사용하기위한 객체 종속성을 관리하고 제공하는 도구입니다. DIC의 주요 이점에는 다음이 포함됩니다. 1. 디커플링, 구성 요소 독립적 인 코드는 유지 관리 및 테스트가 쉽습니다. 2. 유연성, 의존성을 교체 또는 수정하기 쉽습니다. 3. 테스트 가능성, 단위 테스트를 위해 모의 객체를 주입하기에 편리합니다.

SPL SplfixedArray 및 일반 PHP 어레이에 비해 성능 특성을 설명하십시오.SPL SplfixedArray 및 일반 PHP 어레이에 비해 성능 특성을 설명하십시오.Apr 10, 2025 am 09:37 AM

SplfixedArray는 PHP의 고정 크기 배열로, 고성능 및 메모리 사용이 필요한 시나리오에 적합합니다. 1) 동적 조정으로 인한 오버 헤드를 피하기 위해 생성 할 때 크기를 지정해야합니다. 2) C 언어 배열을 기반으로 메모리 및 빠른 액세스 속도를 직접 작동합니다. 3) 대규모 데이터 처리 및 메모리에 민감한 환경에 적합하지만 크기가 고정되어 있으므로주의해서 사용해야합니다.

PHP는 파일 업로드를 어떻게 단단히 처리합니까?PHP는 파일 업로드를 어떻게 단단히 처리합니까?Apr 10, 2025 am 09:37 AM

PHP는 $ \ _ 파일 변수를 통해 파일 업로드를 처리합니다. 보안을 보장하는 방법에는 다음이 포함됩니다. 1. 오류 확인 확인, 2. 파일 유형 및 크기 확인, 3 파일 덮어 쓰기 방지, 4. 파일을 영구 저장소 위치로 이동하십시오.

Null Coalescing 연산자 (??) 및 Null Coalescing 할당 연산자 (?? =)은 무엇입니까?Null Coalescing 연산자 (??) 및 Null Coalescing 할당 연산자 (?? =)은 무엇입니까?Apr 10, 2025 am 09:33 AM

JavaScript에서는 NullCoalescingOperator (??) 및 NullCoalescingAssignmentOperator (?? =)를 사용할 수 있습니다. 1. 2. ??= 변수를 오른쪽 피연산자의 값에 할당하지만 변수가 무효 또는 정의되지 않은 경우에만. 이 연산자는 코드 로직을 단순화하고 가독성과 성능을 향상시킵니다.

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를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

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

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.