redis队列例子详解

测试的时候我用的是Win环境,目前Redis官方是没有Redis环境安装包下载,但是庆幸的是微软有团队在维护Redis WinX64环境的版本,下面是下载网址:

Redis Windows环境下载:
https://github.com/MSOpenTech/redis/releases

下载直接执行redis-server.exe即可

还需要PHP-redis.dll的插件,下载复制到ext目录下,并且在php.ini增加一行:

extension=php_redis.dll

使用的代码非常简单,以下是一个简单的使用类,如果实用在正式环境中,可能要需要进行优化:

class RedisEx{

private $_redis = null;
private $_host = “127.0.0.1”;
private $_prot = 6379;

function __construct(){
self::_connect();
}

public function push($key,$val){
self::_connect();

if($key&&$val){
return $this->_redis->lPush($key,$val);
}
return null;
}

public function pop($key) {
self::_connect();

return $this->_redis->rPop($key);
}

private function _connect(){
if(!$this->_redis){
$this->_redis = new Redis();
$this->_redis->connect($this->_host,$this->_prot);
}
}
}

 

有了处理类,那么我们需要写一个操作代码:

<?php
/**
* http://test.com/1.php?a=POST&key=key1&val=a0000001//加入队列
* http://test.com/1.php?a=GET&key=key1//取出队列
* @var unknown
*/
$action = $_GET[‘a’];

$redisEx = new RedisEx();

if(strtoupper($action) == ‘POST’){
$key = $_GET[‘key’];
$val = $_GET[‘val’];

$res = $redisEx->push($key, $val);

echo $res;

}elseif (strtoupper($action) == ‘GET’){

$key = $_GET[‘key’];

$res = $redisEx->pop($key);

echo $res;
}

echo ‘succ';

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |