찾다
백엔드 개발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 세션에 어떤 데이터를 저장할 수 있습니까?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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

맨티스BT

맨티스BT

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

SecList

SecList

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