memcacheQueue.class.php
/**
* PHP memcache 队列类
* @author LKK/lianq.net
* @version 0.3
* @修改说明:
* 1.放弃了之前的AB面轮值思路,使用类似数组的构造,重写了此类.
* 2.队列默认先进先出,但增加了反向读取功能.
* 3.感谢网友FoxHunter提出的宝贵意见.
* @example:
* $obj = new memcacheQueue('duilie');
* $obj->add('1asdf');
* $obj->getQueueLength();
* $obj->read(10);
* $obj->get(8);
*/
class memcacheQueue{
public static $client; //memcache客户端连接
public $access; //队列是否可更新
private $expire; //过期时间,秒,1~2592000,即30天内
private $sleepTime; //等待解锁时间,微秒
private $queueName; //队列名称,唯一值
private $retryNum; //重试次数,= 10 * 理论并发数
public $currentHead; //当前队首值
public $currentTail; //当前队尾值
const MAXNUM = 20000; //最大队列数,建议上限10K
const HEAD_KEY = '_lkkQueueHead_'; //队列首kye
const TAIL_KEY = '_lkkQueueTail_'; //队列尾key
const VALU_KEY = '_lkkQueueValu_'; //队列值key
const LOCK_KEY = '_lkkQueueLock_'; //队列锁key
/**
* 构造函数
* @param string $queueName 队列名称
* @param int $expire 过期时间
* @param array $config memcache配置
*
* @return
*/
public function __construct($queueName ='',$expire=0,$config =''){
if(empty($config)){
self::$client = memcache_pconnect('127.0.0.1',11211);
}elseif(is_array($config)){//array('host'=>'127.0.0.1','port'=>'11211')
self::$client = memcache_pconnect($config['host'],$config['port']);
}elseif(is_string($config)){//"127.0.0.1:11211"
$tmp = explode(':',$config);
$conf['host'] = isset($tmp[0]) ? $tmp[0] : '127.0.0.1';
$conf['port'] = isset($tmp[1]) ? $tmp[1] : '11211';
self::$client = memcache_pconnect($conf['host'],$conf['port']);
}
if(!self::$client) return false;
ignore_user_abort(true);//当客户断开连接,允许继续执行
set_time_limit(0);//取消脚本执行延时上限
$this->access = false;
$this->sleepTime = 1000;
$expire = empty($expire) ? 3600 : intval($expire)+1;
$this->expire = $expire;
$this->queueName = $queueName;
$this->retryNum = 1000;
$this->head_key = $this->queueName . self::HEAD_KEY;
$this->tail_key = $this->queueName . self::TAIL_KEY;
$this->lock_key = $this->queueName . self::LOCK_KEY;
$this->_initSetHeadNTail();
}
/**
* 初始化设置队列首尾值
*/
private function _initSetHeadNTail(){
//当前队列首的数值
$this->currentHead = memcache_get(self::$client, $this->head_key);
if($this->currentHead === false) $this->currentHead =0;
//当前队列尾的数值
$this->currentTail = memcache_get(self::$client, $this->tail_key);
if($this->currentTail === false) $this->currentTail =0;
}
/**
* 当取出元素时,改变队列首的数值
* @param int $step 步长值
*/
private function _changeHead($step=1){
$this->currentHead += $step;
memcache_set(self::$client, $this->head_key,$this->currentHead,false,$this->expire);
}
/**
* 当添加元素时,改变队列尾的数值
* @param int $step 步长值
* @param bool $reverse 是否反向
* @return null
*/
private function _changeTail($step=1, $reverse =false){
if(!$reverse){
$this->currentTail += $step;
}else{
$this->currentTail -= $step;
}
memcache_set(self::$client, $this->tail_key,$this->currentTail,false,$this->expire);
}
/**
* 队列是否为空
* @return bool
*/
private function _isEmpty(){
return (bool)($this->currentHead === $this->currentTail);
}
/**
* 队列是否已满
* @return bool
*/
private function _isFull(){
$len = $this->currentTail - $this->currentHead;
return (bool)($len === self::MAXNUM);
}
/**
* 队列加锁
*/
private function _getLock(){
if($this->access === false){
while(!memcache_add(self::$client, $this->lock_key, 1, false, $this->expire) ){
usleep($this->sleepTime);
@$i++;
if($i > $this->retryNum){//尝试等待N次
return false;
break;
}
}
$this->_initSetHeadNTail();
return $this->access = true;
}
return $this->access;
}
/**
* 队列解锁
*/
private function _unLock(){
memcache_delete(self::$client, $this->lock_key, 0);
$this->access = false;
}
/**
* 获取当前队列的长度
* 该长度为理论长度,某些元素由于过期失效而丢失,真实长度 * @return int
*/
public function getQueueLength(){
$this->_initSetHeadNTail();
return intval($this->currentTail - $this->currentHead);
}
/**
* 添加队列数据
* @param void $data 要添加的数据
* @return bool
*/
public function add($data){
if(!$this->_getLock()) return false;
if($this->_isFull()){
$this->_unLock();
return false;
}
$value_key = $this->queueName . self::VALU_KEY . strval($this->currentTail +1);
$result = memcache_set(self::$client, $value_key, $data, MEMCACHE_COMPRESSED, $this->expire);
if($result){
$this->_changeTail();
}
$this->_unLock();
return $result;
}
/**
* 读取队列数据
* @param int $length 要读取的长度(反向读取使用负数)
* @return array
*/
public function read($length=0){
if(!is_numeric($length)) return false;
$this->_initSetHeadNTail();
if($this->_isEmpty()){
return false;
}
if(empty($length)) $length = self::MAXNUM;//默认所有
$keyArr = array();
if($length >0){//正向读取(从队列首向队列尾)
$tmpMin = $this->currentHead;
$tmpMax = $tmpMin + $length;
for($i= $tmpMin; $i $keyArr[] = $this->queueName . self::VALU_KEY . $i;
}
}else{//反向读取(从队列尾向队列首)
$tmpMax = $this->currentTail;
$tmpMin = $tmpMax + $length;
for($i= $tmpMax; $i >$tmpMin; $i--){
$keyArr[] = $this->queueName . self::VALU_KEY . $i;
}
}
$result = @memcache_get(self::$client, $keyArr);
return $result;
}
/**
* 取出队列数据
* @param int $length 要取出的长度(反向读取使用负数)
* @return array
*/
public function get($length=0){
if(!is_numeric($length)) return false;
if(!$this->_getLock()) return false;
if($this->_isEmpty()){
$this->_unLock();
return false;
}
if(empty($length)) $length = self::MAXNUM;//默认所有
$length = intval($length);
$keyArr = array();
if($length >0){//正向读取(从队列首向队列尾)
$tmpMin = $this->currentHead;
$tmpMax = $tmpMin + $length;
for($i= $tmpMin; $i $keyArr[] = $this->queueName . self::VALU_KEY . $i;
}
$this->_changeHead($length);
}else{//反向读取(从队列尾向队列首)
$tmpMax = $this->currentTail;
$tmpMin = $tmpMax + $length;
for($i= $tmpMax; $i >$tmpMin; $i--){
$keyArr[] = $this->queueName . self::VALU_KEY . $i;
}
$this->_changeTail(abs($length), true);
}
$result = @memcache_get(self::$client, $keyArr);
foreach($keyArr as $v){//取出之后删除
@memcache_delete(self::$client, $v, 0);
}
$this->_unLock();
return $result;
}
/**
* 清空队列
*/
public function clear(){
if(!$this->_getLock()) return false;
if($this->_isEmpty()){
$this->_unLock();
return false;
}
$tmpMin = $this->currentHead--;
$tmpMax = $this->currentTail++;
for($i= $tmpMin; $i $tmpKey = $this->queueName . self::VALU_KEY . $i;
@memcache_delete(self::$client, $tmpKey, 0);
}
$this->currentTail = $this->currentHead = 0;
memcache_set(self::$client, $this->head_key,$this->currentHead,false,$this->expire);
memcache_set(self::$client, $this->tail_key,$this->currentTail,false,$this->expire);
$this->_unLock();
}
/*
* 清除所有memcache缓存数据
*/
public function memFlush(){
memcache_flush(self::$client);
}
}//end class

phpsession 실패 이유에는 구성 오류, 쿠키 문제 및 세션 만료가 포함됩니다. 1. 구성 오류 : 올바른 세션을 확인하고 설정합니다. 2. 쿠키 문제 : 쿠키가 올바르게 설정되어 있는지 확인하십시오. 3. 세션 만료 : 세션 시간을 연장하기 위해 세션을 조정합니다 .GC_MAXLIFETIME 값을 조정하십시오.

PHP에서 세션 문제를 디버그하는 방법 : 1. 세션이 올바르게 시작되었는지 확인하십시오. 2. 세션 ID의 전달을 확인하십시오. 3. 세션 데이터의 저장 및 읽기를 확인하십시오. 4. 서버 구성을 확인하십시오. 세션 ID 및 데이터를 출력, 세션 파일 컨텐츠보기 등을 통해 세션 관련 문제를 효과적으로 진단하고 해결할 수 있습니다.

Session_Start ()로 여러 통화를하면 경고 메시지와 가능한 데이터 덮어 쓰기가 발생합니다. 1) PHP는 세션이 시작되었다는 경고를 발행합니다. 2) 세션 데이터의 예상치 못한 덮어 쓰기를 유발할 수 있습니다. 3) Session_status ()를 사용하여 반복 통화를 피하기 위해 세션 상태를 확인하십시오.

SESSION.GC_MAXLIFETIME 및 SESSION.COOKIE_LIFETIME을 설정하여 PHP에서 세션 수명을 구성 할 수 있습니다. 1) SESSION.GC_MAXLIFETIME 서버 측 세션 데이터의 생존 시간을 제어합니다. 2) 세션 .Cookie_Lifetime 클라이언트 쿠키의 수명주기를 제어합니다. 0으로 설정하면 브라우저가 닫히면 쿠키가 만료됩니다.

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

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

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