安裝
開始在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 sucessfully"; //查看服務是否運行 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 sucessfully"; //設定 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 sucessfully"; //儲存資料到列表中 $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 sucessfully"; // 擷取資料並輸出 $arList = $redis->keys("*"); echo "Stored keys in redis:: "; print_r($arList);?>執行指令碼,輸出結果為:
Connection to server sucessfullyStored string in redis::tutorial-nametutorial-list