安装
在 PHP 中正式使用 Redis 之前,先确认基础环境已经准备好:Redis 服务端需要先完成安装,PHP 的 Redis 扩展也要提前配置到位,同时本机 PHP 运行环境必须可以正常工作。把这些前置条件都处理好之后,再进行下一步——安装 PHP Redis 扩展,下载地址为:https://github.com/phpredis/phpredis/releases。
PHP安装redis扩展
以下操作需要在下载的 phpredis 目录中完成:
$ wget https://github.com/phpredis/phpredis/archive/3.1.4.tar.gz
$ tar zxvf 3.1.4.tar.gz # 解压
$ cd phpredis-3.1.4 # 进入 phpredis 目录
$ /usr/local/php/bin/phpize # php安装后的路径
$ ./configure --with-php-config=/usr/local/php/bin/php-config
$ make && make install
修改php.ini文件
vi /usr/local/php/lib/php.ini
增加如下内容:
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-zts-20090626"
extension=redis.so
安装完成后重启 php-fpm 或 Apache。通过查看 phpinfo 信息,就可以看到 Redis 扩展已经生效。

连接到 redis 服务
实例
connect('127.0.0.1', 6379);
echo "Connection to server successfully";
//查看服务是否运行
echo "Server is running: " . $redis->ping();
?>
执行脚本后,输出结果如下:
Connection to server successfully
Server is running: PONG
Redis PHP String(字符串) 实例
实例
connect('127.0.0.1', 6379);
echo "Connection to server successfully";
//设置 redis 字符串数据
$redis->set("tutorial-name", "Redis tutorial");
// 获取存储的数据并输出
echo "Stored string in redis:: " . $redis->get("tutorial-name");
?>
执行脚本后,输出结果如下:
Connection to server successfully
Stored string in redis:: Redis tutorial
Redis PHP List(列表) 实例
实例
connect('127.0.0.1', 6379);
echo "Connection to server successfully";
//存储数据到列表中
$redis->lpush("tutorial-list", "Redis");
$redis->lpush("tutorial-list", "Mongodb");
$redis->lpush("tutorial-list", "Mysql");
// 获取存储的数据并输出
$arList = $redis->lrange("tutorial-list", 0 ,5);
echo "Stored string in redis";
print_r($arList);
?>
执行脚本后,输出结果如下:
Connection to server successfully
Stored string in redis
Mysql
Mongodb
Redis
Redis PHP Keys 实例
实例
connect('127.0.0.1', 6379);
echo "Connection to server successfully";
// 获取数据并输出
$arList = $redis->keys("*");
echo "Stored keys in redis:: ";
print_r($arList);
?>
执行脚本后,输出结果如下:
Connection to server successfully
Stored string in redis::
tutorial-name
tutorial-list