安装
要在PHP程序中使用Redis,首先需要确保 Redis 的PHP驱动程序和 PHP 安装设置在机器上。可以查看 PHP教程 教你如何在机器上安装PHP。现在,让我们来看看一下如何设置 Redis 的PHP驱动程序。
需要从 github 上资料库: https://github.com/nicolasff/phpredis 下载 phpredis。下载完成以后,将文件解压缩到 phpredis 目录。在 Ubuntu 上安装这个扩展,可使用如下图所示的命令来安装。
1cd phpredis 2sudo phpize 3sudo ./configure 4sudo make 5sudo make install
现在,复制和粘贴“modules”文件夹的内容复制到PHP扩展目录中,并在 php.ini 中添加以下几行。
extension = redis.so
现在 Redis 和 PHP 安装完成
连接到Redis服务器
1<?php 2 //Connecting to Redis server on localhost 3 $redis = new Redis(); 4 $redis->connect('127.0.0.1', 6379); 5 echo "Connection to server sucessfully"; 6 //check whether server is running or not 7 echo "Server is running: " . $redis->ping(); 8?> 9 10当执行程序时,会产生下面的结果: 11 12 13Connection to server sucessfully 14Server is running: PONG
Redis的PHP字符串实例
1<?php 2 //Connecting to Redis server on localhost 3 $redis = new Redis(); 4 $redis->connect('127.0.0.1', 6379); 5 echo "Connection to server sucessfully"; 6 //set the data in redis string 7 $redis->set("tutorial-name", "Redis tutorial"); 8 // Get the stored data and print it 9 echo "Stored string in redis:: " . $redis.get("tutorial-name"); 10?> 11 12当执行程序时,会产生下面的结果: 13 14 15Connection to server sucessfully 16Stored string in redis:: Redis tutorial
Redis的PHP列表示例
1<?php 2 //Connecting to Redis server on localhost 3 $redis = new Redis(); 4 $redis->connect('127.0.0.1', 6379); 5 echo "Connection to server sucessfully"; 6 //store data in redis list 7 $redis->lpush("tutorial-list", "Redis"); 8 $redis->lpush("tutorial-list", "Mongodb"); 9 $redis->lpush("tutorial-list", "Mysql"); 10 // Get the stored data and print it 11 $arList = $redis->lrange("tutorial-list", 0 ,5); 12 echo "Stored string in redis:: " 13 print_r($arList); 14?> 15 16当执行程序时,会产生下面的结果: 17 18 19Connection to server sucessfully 20Stored string in redis:: 21Redis 22Mongodb 23Mysql
Redis的PHP键例
1<?php 2 //Connecting to Redis server on localhost 3 $redis = new Redis(); 4 $redis->connect('127.0.0.1', 6379); 5 echo "Connection to server sucessfully"; 6 // Get the stored keys and print it 7 $arList = $redis->keys("*"); 8 echo "Stored keys in redis:: " 9 print_r($arList); 10?> 11 12当执行程序时,会产生下面的结果: 13 14 15Connection to server sucessfully 16Stored string in redis:: 17tutorial-name 18tutorial-list