安装
开始在 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$ 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 做事
<?php //连接本地的 Redis 做事 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo \"大众Connection to server successfully\"大众; //查看做事是否运行 echo \"大众Server is running: \"大众 . $redis->ping();?>
实行脚本,输出结果为:
Connection to server sucessfullyServer is running: PONG
Redis PHP String(字符串) 实例
<?php //连接本地的 Redis 做事 $redis = new Redis(); $redis->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 sucessfullyStored string in redis:: Redis tutorial
Redis PHP List(列表) 实例
<?php //连接本地的 Redis 做事 $redis = new Redis(); $redis->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 sucessfullyStored string in redisMysqlMongodbRedis
Redis PHP Keys 实例
<?php //连接本地的 Redis 做事 $redis = new Redis(); $redis->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 sucessfullyStored string in redis::tutorial-nametutorial-list