在phpstudy上安装redis扩展以及TP3.2调用redis方法

redis下载地址 https://github.com/microsoftarchive/redis/releases

根据你的windows系统来下载redis(x64或者x86两种),我这边下载的是Redis-x64-3.2.100.zip(根据自己需求来下载)。下载完毕后将压缩包解压到自己要放到的位置即可

然后在该目录下使用shift+鼠标右键选择在此处打开cmd

然后 运行 redis-server.exe redis.windows.conf

在该目录下使用shift+鼠标右键再次运行cmd,然后在运行 redis-cli.exe -h 127.0.0.1 -p 6379 或者直接输入redis-cli.exe·

以上两个窗口请勿关闭哦,不然无法运行的

扩展下载地址 https://pecl.php.net/package/redis

下载的过程,需要你选择有你电脑的版本,更重要的是要有你php版本号的文件,如下面redis4.3.0版本并没有php7.0版本,所以你要选择redis其他版本

在本地输入localhost/phpinfo.php查看自己的信息NTS是非线程 ,TS则是线程(x84和x64的区别肯定都知道的)

所以我们选择php7.0的下载

然后将解压的这两个文件

放到以下目录中

之后在配置php.ini

后面再次访问phpinfo.php文件,如果有

说明配置成功,可以调用redis尝试一下。

然后我在TP3.2框架中运行以下代码

方法一

这个方法有一点就是每次运行redis就要开启这些,有些麻烦

$redis=new \Redis();
$redis->connect('127.0.0.1',6379);
echo "server is running:".$redis->ping();
echo '<br/>';
$redis->set('users','123',3600);
$user_name=$redis->get('users');
var_dump($user_name);exit;

就会打印出

方法二

直接在config中配置好,下回在控制器中可以直接调用即可

在ThinkPHP/Library/Think/Cache/Driver中添加一个Redis.class.php,以下就是这个文件中的代码

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2013 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
defined('THINK_PATH') or exit();

/**
 * Redis缓存驱动 
 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
 */
class Redis extends Cache {
    /**
    * 架构函数
     * @param array $options 缓存参数
     * @access public
     */
    public function __construct($options=array()) {
        if ( !extension_loaded('redis') ) {
            E(L('_NOT_SUPPERT_').':redis');
        }
        if(empty($options)) {
            $options = array (
                'host'          => C('REDIS_HOST') ? C('REDIS_HOST') : '127.0.0.1',
                'port'          => C('REDIS_PORT') ? C('REDIS_PORT') : 6379,
                'timeout'       => C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false,
                'persistent'    => false,
            );
        }
        $this->options =  $options;
        $this->options['expire'] =  isset($options['expire'])?  $options['expire']  :   C('DATA_CACHE_TIME');
        $this->options['prefix'] =  isset($options['prefix'])?  $options['prefix']  :   C('DATA_CACHE_PREFIX');        
        $this->options['length'] =  isset($options['length'])?  $options['length']  :   0;        
        $func = $options['persistent'] ? 'pconnect' : 'connect';
        $this->handler  = new \Redis;
        $options['timeout'] === false ?
            $this->handler->$func($options['host'], $options['port']) :
            $this->handler->$func($options['host'], $options['port'], $options['timeout']);
    }

    /**
     * 读取缓存
     * @access public
     * @param string $name 缓存变量名
     * @return mixed
     */
    public function get($name) {
        N('cache_read',1);
        $value = $this->handler->get($this->options['prefix'].$name);
        $jsonData  = json_decode( $value, true );
        return ($jsonData === NULL) ? $value : $jsonData;  //检测是否为JSON数据 true 返回JSON解析数组, false返回源数据
    }

    /**
     * 写入缓存
     * @access public
     * @param string $name 缓存变量名
     * @param mixed $value  存储数据
     * @param integer $expire  有效时间(秒)
     * @return boolean
     */
    public function set($name, $value, $expire = null) {
        N('cache_write',1);
        if(is_null($expire)) {
            $expire  =  $this->options['expire'];
        }
        $name   =   $this->options['prefix'].$name;
        //对数组/对象数据进行缓存处理,保证数据完整性
        $value  =  (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        if(is_int($expire)) {
            $result = $this->handler->setex($name, $expire, $value);
        }else{
            $result = $this->handler->set($name, $value);
        }
        if($result && $this->options['length']>0) {
            // 记录缓存队列
            $this->queue($name);
        }
        return $result;
    }

    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function rm($name) {
        return $this->handler->delete($this->options['prefix'].$name);
    }

    /**
     * 清除缓存
     * @access public
     * @return boolean
     */
    public function clear() {
        return $this->handler->flushDB();
    }

}

在ThinkPHP/Library/Think/Session/Driver中添加一个Redis.class.php,以下就是这个文件中的代码

<?php

namespace Think\Session\Driver;

class Redis
{
    /**
     * Redis句柄
     */
    private $handler;
    private $get_result;

    public function __construct(){
        if ( !extension_loaded('redis') ) {
            E(L('_NOT_SUPPERT_').':redis');
        }
        if(empty($options)) {
            $options = array (
                'host'          => C('REDIS_HOST') ? C('REDIS_HOST') : '127.0.0.1',
                'port'          => C('REDIS_PORT') ? C('REDIS_PORT') : 6379,
                'timeout'       => C('REDIS_TIMEOUT') ? C('REDIS_TIMEOUT') : false,
                'persistent'    => C('REDIS_PERSISTENT') ? C('REDIS_PERSISTENT') : false,
                'auth'      => C('REDIS_AUTH') ? C('REDIS_AUTH') : false,
            );
        }
        $options['host'] = explode(',', $options['host']);
        $options['port'] = explode(',', $options['port']);
        $options['auth'] = explode(',', $options['auth']);
        foreach ($options['host'] as $key=>$value) {
            if (!isset($options['port'][$key])) {
                $options['port'][$key] = $options['port'][0];
            }
            if (!isset($options['auth'][$key])) {
                $options['auth'][$key] = $options['auth'][0];
            }
        }
        $this->options =  $options;
        $expire = C('SESSION_EXPIRE');
        $this->options['expire'] =  isset($expire) ? (int)$expire : (int)ini_get('session.gc_maxlifetime');;
        $this->options['prefix'] =  isset($options['prefix']) ?  $options['prefix']  :   C('SESSION_PREFIX');
        $this->handler  = new \Redis;
    }

    /**
     * 连接Redis服务端
     * @access public
     * @param bool $is_master : 是否连接主服务器
     */
    public function connect($is_master = true) {
        if ($is_master) {
            $i = 0;
        } else {
            $count = count($this->options['host']);
            if ($count == 1) {
                $i = 0;
            } else {
                $i = rand(1, $count - 1);   //多个从服务器随机选择
            }
        }
        $func = $this->options['persistent'] ? 'pconnect' : 'connect';
        try {
            if ($this->options['timeout'] === false) {
                $result = $this->handler->$func($this->options['host'][$i], $this->options['port'][$i]);
                if (!$result)
                    throw new \Think\Exception('Redis Error', 100);
            } else {
                $result = $this->handler->$func($this->options['host'][$i], $this->options['port'][$i], $this->options['timeout']);
                if (!$result)
                    throw new \Think\Exception('Redis Error', 101);
            }
            if ($this->options['auth'][$i]) {
                $result = $this->handler->auth($this->options['auth'][$i]);
                if (!$result) {
                    throw new \Think\Exception('Redis Error', 102);
                }
            }
        } catch ( \Exception $e ) {
            exit('Error Message:'.$e->getMessage().'<br>Error Code:'.$e->getCode().'');
        }
    }

    /**
    +----------------------------------------------------------
     * 打开Session
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param string $savePath
     * @param mixed $sessName
    +----------------------------------------------------------
     */
    public function open($savePath, $sessName) {
        return true;
    }

    /**
    +----------------------------------------------------------
     * 关闭Session
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     */
    public function close() {
        if ($this->options['persistent'] == 'pconnect') {
            $this->handler->close();
        }
        return true;
    }

    /**
    +----------------------------------------------------------
     * 读取Session
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param string $sessID
    +----------------------------------------------------------
     */
    public function read($sessID) {
        $this->connect(0);
        $this->get_result = $this->handler->get($this->options['prefix'].$sessID);
        //延长有效期
        $this->handler->expire($this->options['prefix'].$sessID,C('SESSION_EXPIRE'));
        return $this->get_result;
    }

    /**
    +----------------------------------------------------------
     * 写入Session
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param string $sessID
     * @param String $sessData
    +----------------------------------------------------------
     */
    public function write($sessID, $sessData) {
        if (!$sessData || $sessData == $this->get_result) {
            return true;
        }
        $this->connect(1);
        $expire  =  $this->options['expire'];
        $sessID   =   $this->options['prefix'].$sessID;
        if(is_int($expire) && $expire > 0) {
            $result = $this->handler->setex($sessID, $expire, $sessData);
            $re = $result ? 'true' : 'false';
        }else{
            $result = $this->handler->set($sessID, $sessData);
            $re = $result ? 'true' : 'false';
        }
        return $result;
    }

    /**
    +----------------------------------------------------------
     * 删除Session
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param string $sessID
    +----------------------------------------------------------
     */
    public function destroy($sessID) {
        $this->connect(1);
        return $this->handler->delete($this->options['prefix'].$sessID);
    }

    /**
    +----------------------------------------------------------
     * Session 垃圾回收
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param string $sessMaxLifeTime
    +----------------------------------------------------------
     */
    public function gc($sessMaxLifeTime) {
        return true;
    }

    /**
    +----------------------------------------------------------
     * 打开Session
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param string $savePath
     * @param mixed $sessName
    +----------------------------------------------------------
     */
    public function execute() {
        session_set_save_handler(
            array(&$this, "open"),
            array(&$this, "close"),
            array(&$this, "read"),
            array(&$this, "write"),
            array(&$this, "destroy"),
            array(&$this, "gc")
        );
    }

    public function __destruct() {
        if ($this->options['persistent'] == 'pconnect') {
            $this->handler->close();
        }
        session_write_close();
    }

}

然后在config中配置以下参数即可

/* SESSION配置 */
'SESSION_AUTO_START' => true, //是否开启session
'SESSION_TYPE'          =>  'Redis',    //session 驱动
'SESSION_EXPIRE'        =>  '7200',        //session有效期(单位:秒) 0表示永久缓存,当session被访问时,时间重新计算。
'SESSION_PREFIX' => 'onethink_home', //session前缀

//缓存 配置
'DATA_CACHE_TYPE'=>'Redis',//默认动态缓存为Redis
'DATA_CACHE_PREFIX' => 'Redis_',//缓存前缀
'DATA_CACHE_TIME'       =>  '0',    //缓存时间 0为永久 当缓存被访问时,时间不重新计算

//Redis 配置
'REDIS_RW_SEPARATE' => true, //Redis读写分离 true 开启
'REDIS_HOST'=>'127.0.0.1', //redis服务器ip,多台用逗号隔开;读写分离开启时,第一台负责写,其它[随机]负责读;
'REDIS_PORT'=>'6379',//端口号
'REDIS_TIMEOUT'=>'30',//超时时间(秒)
'REDIS_PERSISTENT'=>false,//是否长连接 false=短连接
'REDIS_AUTH'=>'',//AUTH认证密码

最后在控制器中调用

$test['a']='123';
$test['b']='1234';
$test['c']['a']='ca123';
$test['c']['b']='cb123';

S('test',$test);
$_SESSION['test']=$test;

echo "S缓存:</ br>";
dump(S('test'));
echo "SESSION:</ br>";
dump($_SESSION['test']);

exit;

打印出 

发布了20 篇原创文章 · 获赞 21 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/jachinFang/article/details/91038623
今日推荐