创建一个redis类
<?php
namespace app\common\auth;
class Redis
{
//实例字典, 以实例名称为KEY, 对象实例为值
protected static $dict = array();
//配置信息
// private $redis = array(
// 'host'=>'172.21.20.13',
// 'port'=>'6379',
// 'timeout'=>'0',
// 'retry'=>'0',
// 'readTimeout'=>'0',
// 'auth'=>'ZJ1X8fZRuQndScDF7rTW'
// );
private $redis = array(
'host'=>'127.0.0.1',
'port'=>'6379',
'timeout'=>'0',
'auth'=>''
);
public function __construct()
{
$this->host ='127.0.0.1'; //主机域名
$this->port ='6379'; //端口
$this->timeout =$this->redis['timeout']; //连接超时时间,以秒为单位, 默认0为无限
// $this->retry =$this->redis['retry']; //连接重试间隔时间, 以毫秒为单位
// $this->readTimeout =$this->redis['readTimeout']; //读超时时间,以秒为单位, 默认0无限
$this->auth =''; //检测给定的密码和配置文件中的密码是否相符,//设置密码
}
/**
* 获取数据库单实例
* @param [ $name ] 实例名
* @param [ $className ] 类名
* @param [ $data ] 构造函数参数
* @return object 单例对象实例
*/
public static function getInstance($name, $data = array())
{
if (!$name) {
return null;
}
if (!isset(self::$dict[$name])) {
if ($data) {
self::$dict[$name]= new \Redis($data);
} else {
self::$dict[$name]= new \Redis();
}
}
return self::$dict[$name];
}
/**
* 取得redis client
*
* @param [ $name ] 实例名字
*
* @return object redis
*/
public function getClient($name = 'redis')
{
$redis = self::getInstance($name);
if (!isset($this->host)) {
return false;
}
$host = $this->host;
//连接端口,默认为6379
$port = 6379;
if (isset($this->port)) {
$port = intval($this->port);
}
//连接超时时间,以秒为单位, 默认0为无限
$timeout = 0;
if (isset($this->timeout)) {
$timeout = intval($this->timeout);
}
//连接重试间隔时间, 以毫秒为单位
// $retry = 0;
// if (isset($this->retry)) {
// $retry = intval($this->retry);
// }
//读超时时间,以秒为单位, 默认0无限
// $readTimeout = 0;
// if (isset($this->readTimeout)) {
// $readTimeout = floatval($this->readTimeout);
// }
if (!$redis->connect($host, $port, $timeout)) {
return false;
}
return $redis;
}
}
控制器中
use app\common\auth\Redis;
$RedisClient = new Redis();
$redis = $RedisClient->getClient();
if (!$redis) {
return false;
}
// $redis->lPush('msg','rferfwerf');
dump($redis->lPop('msg'));
over over

本文详细介绍了如何在ThinkPHP5.1框架中集成并使用Redis,从创建Redis类到在控制器中的实际应用,帮助开发者实现高效的数据缓存操作。
3万+

被折叠的 条评论
为什么被折叠?



