要在PHP程序中使用Redis,首先需要确保 Redis 的PHP驱动程序和 PHP 安装设置在机器上。可以查看 PHP教程 教你如何在机器上安装PHP。可以使用phpinfo()查看是否已经安装了redis。
下载 phpredis
https://pecl.php.net/package/redis
或者从 github 上资料库: https://github.com/nicolasff/phpredis 。
下载完成以后,将文件解压缩到 phpredis 目录。在 Ubuntu 上安装这个扩展,可使用如下图所示的命令来安装。
1 2 3 4 5 6 |
cd phpredis phpize ./configure (一般不行) ./configure --with-php-config=/usr/local/php/bin/php-config (用这个) make make install |
现在,复制和粘贴“modules”文件夹的内容复制到PHP扩展目录中,并在 php.ini 中添加以下几行。
1 2 3 4 5 6 7 |
cp modules/redis.so /usr/local/php/lib/php/extensions/no-debug-non-zts-20151012/ php.ini添加下面 extension = redis.so 或者下面这个 ;[phpredis] extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20151012/redis.so |
连接到Redis服务器
1 2 3 4 5 6 7 8 |
<?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; //check whether server is running or not echo "Server is running: " . $redis->ping(); ?> |
当执行程序时,会产生下面的结果:
1 2 |
Connection to server sucessfully Server is running: PONG |
Redis的PHP字符串实例
1 2 3 4 5 6 7 8 9 10 |
<?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully<br/>"; //set the data in redis string $redis->set("tutorial-name", "Redis tutorial"); // Get the stored data and print it echo "Stored string in redis:: " . $redis->get("tutorial-name"); ?> |
当执行程序时,会产生下面的结果:
1 2 |
Connection to server sucessfully Stored string in redis:: Redis tutorial |
Redis的PHP列表示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully<br/>"; //store data in redis list $redis->lpush("tutorial-list", "Redis"); $redis->lpush("tutorial-list", "Mongodb"); $redis->lpush("tutorial-list", "Mysql"); // Get the stored data and print it $arList = $redis->lrange("tutorial-list", 0 ,2); echo "Stored string in redis:: <br/>"; print_r($arList); ?> |
当执行程序时,会产生下面的结果:
1 2 3 4 5 |
Connection to server sucessfully Stored string in redis:: mysql Mongodb redis |
Redis的PHP键例
1 2 3 4 5 6 7 8 9 10 |
<?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully<br/>"; // Get the stored keys and print it $arList = $redis->keys("*"); echo "Stored keys in redis:: <br/>"; print_r($arList); ?> |
当执行程序时,会产生下面的结果:
1 2 3 4 5 |
Connection to server sucessfully Stored string in redis:: tutorial-list tutorial-name a |
更多待涛哥实践总结分享,此处应有掌声
转载请注明:PHP笔记 » 安装Redis驱动及PHP连接Redis服务器操作