目录

安装Redis+PHP连接Redis

安装Redis + PHP连接Redis

花了两天的时间,看了无数的English code,终于在自己的笔记本上装上了Redis,下面奉上教程。

首先,不懂Redis干嘛用的请先百度…

下载Redis的windows32位客户端:windows32位Redis客户端

下载后建议解压到web目录之类的地方,譬如:D:\WWW\Redis

为了省去用CMD进入文件夹的麻烦可以直接进入到你的Redis文件夹下shift+鼠标右键(如右图)

http://blog.sky31.com/wp-content/uploads/2014/03/GIGXT_UPZ9PE@A9FX5-300x144.jpg

接着输入以下指令(redis.conf为redis的配置文件,有需要的可以修改过后运行,这个是我从网上copy下来改好能用的):

http://blog.sky31.com/wp-content/uploads/2014/03/QQ%E5%9B%BE%E7%89%8720140304215540-300x92.jpg

如果你能看到CMD显示以下内容,恭喜你,你的Redis服务端已经能用了:

http://blog.sky31.com/wp-content/uploads/2014/03/91@_L9N2YHZHI2PASAN-300x196.jpg

以后要使用都可以用这个指令开启Redis,当然窗口不能关闭,关闭窗口Redis会停止运行。

Then,建立PHP到Redis的连接,使PHP能够直接往Redis里发送数据:

请运行phpinfo()查看以下内容:PHP版本号、TS or NTS、VC版本

http://blog.sky31.com/wp-content/uploads/2014/03/DDKDSKWBJLIKIJCKFS-300x50.jpg

请选择对应的版本下载

PHP5.4连接Redis所需DLL (我自己用的是XAMPP,所以略不同)

php5.3连接Redis所需DLL (WAMP的一般用这个)

下载后请将解压得到的DLL文件copy到php/ext目录下,譬如我的是D:\xampp\php\ext,WAMP的一时想不起具体路径了,请直接搜索文件夹。(PHP5.4下需要两个一起使用,所以我的有两个DLL)

http://blog.sky31.com/wp-content/uploads/2014/03/QQ%E5%9B%BE%E7%89%8720140304221615-300x107.jpg

然后就是修改php.ini了,在你看到的一大堆extension=XXXXX.dll的后面加上以下内容(大意就是让Apache在启动的时候去加载对应扩展):

PHP5.4:(顺序不可颠倒)

extension=php_igbinary.dll
extension=php_redis.dll

PHP5.3:(使用WAMP的请注意,看一下你phpinfo中Loaded Configuration File字段php.ini的真正的调用路径,默认情况下php.ini是加载Apache下的那个php.ini)

extension=php_redis.dll

http://blog.sky31.com/wp-content/uploads/2014/03/QQ%E5%9B%BE%E7%89%8720140304221953-300x250.jpg

字段添加完后保存重启Apache(不重启是不会加载的),然后再看一下你的phpinfo里面是不是能搜到Redis扩展了,如果搜到那就恭喜你,扩展加载成功可以接着下一步了,如果搜不到也恭喜你,回头检查下哪个步骤出了问题。(如图,版本不同可以不用纠结)

http://blog.sky31.com/wp-content/uploads/2014/03/QQ%E5%9B%BE%E7%89%8720140304222802-300x50.jpg

End,测试:

新建一个php文件,输入以下code

<?php
/**
*
* 项目名称:test
* 创建人:Zoa_Chou
* 创建时间:2014-3-3
*
*/

$redis = new Redis();
$redis->connect('127.0.0.1',6379);
//$redis->connect("test.com",6379); //php客户端设置的ip及端口
//存储一个值
$redis->set("say","Hello World");
echo $redis->get("say"); //应输出Hello World

//存储多个值
$array = array('first_key'=>'first_val',
'second_key'=>'second_val',
'third_key'=>'third_val');
$array_get = array('first_key','second_key','third_key');
$redis->mset($array);
var_dump($redis->mget($array_get));
?>

保存,运行。如果看到下图,恭喜你,开始享受你的Redis吧!

![5~]75BKZ@LS}KT1YLFNL9CG](http://blog.sky31.com/wp-content/uploads/2014/03/575BKZ@LSKT1YLFNL9CG-300x34.jpg)

封装好的Redis常用类

这是一个封装好的redis常用类,function里面并没有把所有的都封装,只是把最近项目用到的都封装了而已,这里有个比较完整的,需要可以查看。

因为最近做的项目是基于ThinkPHP框架,所以有少量方法是用的TP的内置方法,当然这一部分很少而且应该有基础的PHPer都能看懂。当然,正是因为是基于TP写的类,所以这个类也可以直接替代官方的redis类使用(官方的方法很少而且不好使)。

另外如果在使用过程中出现redis连接超时的情况各位可以尝试修改PHP的socket超时时间来解决:

ini_set('default_socket_timeout', -1); //避免redis超时无法连接

差不多就这些,最后,奉上redis常用操作类:

<?php
/**
 * User: 佐柱
 * Date: 14-4-17
 */
namespace Admin\Model;
use Think\Model;
class RedisModel extends Model{
    protected $redis = null;
    protected $redisList = 'searchList';
    /*
     * 单例模式初始化Redis
     */
    public function _initialize(){
        //单例模式
        if($this->redis === null){
            $this->redis =  new \Redis();
            if(C('REDIS_CTYPE') == 1){
                $this->redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_CACHE_TIMEOUT'));
            }else{
                $this->redis->pconnect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_CACHE_TIMEOUT'));
            }
            $this->redis->setOption('Redis::OPT_PREFIX', C('REDIS_PREFIX'));//设置每一个key的前缀,区别其他APP
        }
    }
    /*
     * 覆盖存入key-value
     * param string $key 键
     * param string/array $value 值
     * param int    $liveTime 有效时间
     * return true成功,false失败
     */
    public function set($key,$value,$liveTime = 0){
        if(empty($key) || empty($value)){
            $this->error = 'key或value不能为空';
            return false;
        }
        $key = $this->securityFilters($key);
        $value = $this->securityFilters($value);
        //redis的value只能是非数组,数组数据转化成json格式存入
        $value = is_array($value) ? json_encode($value) : $value;
        if($liveTime == 0){
            $this->redis->set($key,$value);
        }else{
            $liveTime = $this->securityFilters($liveTime,true);
            $this->redis->setex($key,$liveTime,$value);
        }
        return true;
    }
    /*
     * 批量覆盖存入key-value
     * param array $array_set 需要存入的数据,格式如下
     * array('key'=>'value')
     * array(0=>array(key =>'key',value =>'value',liveTime =>'liveTime'),1=>array('key','value','liveTime'))
     * param boolean $isLiveTime 是否存在过期时间
     * return array('success' => 0,'failure' => 0)成功,false失败
     */
    public function sets($array_set,$isLiveTime = false){
        $success = 0;//成功条数
        $failure = 0;//失败条数
        if(is_array($array_set)){
            if(!$isLiveTime){//不需要存入过期时间的操作
                //原子性操作
                if($this->redis->mset($array_set)){
                    $success = count($array_set);
                }else{
                    $failure = count($array_set);
                }
            }else{//需要存入过期时间的操作
                unset($value);
                foreach($array_set as $value){
                    if($this->set($value['key'],$value['value'],$value['liveTime'])){
                        $success++;
                    }else{
                        $this->error .= '失败key:'.$value['key'].';';
                        $failure++;
                    }
                }
            }
            return array('success' => $success,'failure' => $failure);
        }else{
            $this->error = '数据格式错误';
            return false;
        }
    }
    /*
     * 返回剩余key生存时间
     * param string $key key
     * return int 剩余生存时间
     */
    public function tll($key){
        $liveTime = $this->redis->tll($key);
        return $liveTime;
    }
    /*
     * 不覆盖存入key-value
     * param array $array_set 需要存入的数据,格式如下
     * array('key'=>'value')
     * array(0=>array(key =>'key',value =>'value',liveTime =>'liveTime'),1=>array('key','value','liveTime'))
     * param boolean $isLiveTime 是否存在过期时间
     * return array('success' => 0,'failure' => 0)成功,false失败
     */
    public function setnx($key,$value,$liveTime = 0){
        if(empty($key) || empty($value)){
            return false;
        }
        $key = $this->securityFilters($key);
        $value = $this->securityFilters($value);
        $value = is_array($value) ? json_encode($value) : $value;
        $this->redis->setnx($key,$value);
        if($liveTime != 0){
            $liveTime = $this->securityFilters($liveTime,true);
            $this->redis->expire($key,$liveTime);
        }
        return true;
    }
    /*
     * 将给定key的值设为value,并返回key的旧值
     * param string $key key
     * param string $newValue 新value
     * return string成功,false失败
     */
    public function getset($key,$newValue){
        $oldValue = '';
        if(!empty($key) && !empty($newValue)){
            $newValue = $this->securityFilters($newValue);
            $newValue = is_array($newValue) ? json_encode($newValue) : $newValue;
            $oldValue = $this->redis->getset($key,$newValue);
            return $oldValue;
        }else{
            $this->error = 'key和value不能为空';
            return false;
        }
    }
    /*
     * 取出value
     * param string $key 键
     * return string成功,false失败
     */
    public function get($key){
        $value = $this->redis->get($key);
        //判断是否为json格式的数据,是则转化回数组
        $value = is_null(json_decode($value)) ? $value :json_decode($value,true);
        return $value;
    }
    /*
     * 批量取出value
     * param array $keys 键
     * return array成功,false失败
     */
    public function gets($keys){
        if(is_array($keys)){
            $tmpValues = $this->redis->mget($keys);
            foreach($tmpValues as $param){
                $values[] = is_null(json_decode($param)) ? $param :json_decode($param,true);
            }
            return $values;
        }else{
            $this->error = '数据格式错误';
            return false;
        }
    }
    /*
     * 是否存在指定key的value
     * param string $key key
     * return true存在,false不存在
     */
    public function exists($key){
        if(!empty($key)){
            $res = $this->redis->exists($key);
            return $res ;
        }else{
            $this->error = '查询key不能为空';
            return false;
        }
    }
    /*
     * 查看所有key-value
     * return array
     */
    public function showKey(){
        $this->redis->keys(C('REDIS_PREFIX').'*');
    }
    /*
     * 删除key
     * param string/array $key key
     * return true成功,false失败
     */
    public function rm($key){
        return $this->redis->del($key);
    }
    /**
     * 数据进栈尾
     * @param array list 进栈数据
     * @param bool isLoop 是否开启循环进栈,true为开启,false为关闭,默认关闭
     * @return string,flase 插入的数据ID,操作出错时返回false
     */
    public function push($list,$isLoop = false){
        if(!$isLoop){
            if (!empty($list)){
                if($list){
                    $this->redis->rPush($this->redisList,$list);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            if (!empty($list)) {
                $ids = array();
                if(isset($value))    unset($value);
                foreach ($list as $key=>$value){
                    $res = $this->push($value,false);
                    if ($res) {
                        $ids[$key] = $res;
                    } else {
                        $ids[$key] = false;
                    }
                }
            }else {
                return false;
            }
        }
    }
    /**
     * 数据出栈
     * @return array,false 栈内数据,栈为空时返回false
     */
    public function pop(){
        $list = $this->redis->lPop($this->redisList);
        if($list){
            return $list;
        } else {
            return false;
        }
    }
    /**
     * 获取栈中还有数据数目
     * @return int,false 返回栈内数据数,栈为空时返回false
     */
    public function listNum(){
        $len = 0;
        $len = $this->redis->lSize($this->redisList);
        if($len){
            return $len;
        } else {
            return false;
        }
    }
    /**
     * 循环取出栈中的所有数据
     * @return array,flase 邮件信息,取完则返回false
     */
    public function fetch_row(){
        $list = array();
        $i = 0;
        while ($this->redis->lGet($this->redisList,$i)){
            $list[] = $this->redis->lGet($this->redisList,$i);
            $i++;
        }
        if (!empty($list)) {
            return $list;
        } else {
            return false;
        }
    }
    /*
     * 清空所有key-value
     */
    public function clear(){
        $this->redis->flushAll();
    }
    /*
     * 字符串、数字安全过滤
     * param string $unsafe 需要过滤的字符串或数字
     * return string|int 过滤后的字符或字符串
     */
    protected function securityFilters($unsafe,$toInt = false){
        if(!$toInt && !is_int($unsafe)){
            if(is_string($unsafe)){
                $safe = addslashes(trim($unsafe));
            }elseif(is_array($unsafe)){
                unset($key);
                unset($value);
                foreach($unsafe as $key => $value){
                    $safe[$this->securityFilters($key)] = $this->securityFilters($value);
                }
            }else{
                    $this->error = '非法数据类型!';
                    return null;
            }
        }else{
            $safe = intval($unsafe);
        }
        return $safe;
    }
}

转载请注明文章出处:https://www.mudoom.com 谢谢:)