Redis PHP連接操作


安裝

要在PHP程序中使用Redis,首先需要確保 Redis 的PHP驅動程序和 PHP 安裝設置在機器上。可以查看 PHP教程 教你如何在機器上安裝PHP。現在,讓我們來看看一下如何設置 Redis 的PHP驅動程序。

需要從 github 上資料庫: https://github.com/nicolasff/phpredis 下載 phpredis。下載完成以后,將文件解壓縮到 phpredis 目錄。在 Ubuntu 上安裝這個擴展,可使用如下圖所示的命令來安裝。


cd phpredis
sudo phpize
sudo ./configure
sudo make
sudo make install

現在,復制和粘貼“modules”文件夾的內容復制到PHP擴展目錄中,並在 php.ini 中添加以下幾行。


extension = redis.so

現在 Redis 和 PHP 安裝完成。

連接到Redis服務器


<?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();
?>

當執行程序時,會產生下面的結果:


Connection to server sucessfully
Server is running: PONG

Redis的PHP字符串實例


<?php
   //Connecting to Redis server on localhost
   $redis = new Redis();
   $redis->connect('127.0.0.1', 6379);
   echo "Connection to server sucessfully";
   //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");
?>

當執行程序時,會產生下面的結果:


Connection to server sucessfully
Stored string in redis:: Redis tutorial

Redis的PHP列表示例


<?php
   //Connecting to Redis server on localhost
   $redis = new Redis();
   $redis->connect('127.0.0.1', 6379);
   echo "Connection to server sucessfully";
   //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 ,5);
   echo "Stored string in redis:: "
   print_r($arList);
?>

當執行程序時,會產生下面的結果:


Connection to server sucessfully
Stored string in redis::
Redis
Mongodb
Mysql

Redis的PHP鍵例


<?php
   //Connecting to Redis server on localhost
   $redis = new Redis();
   $redis->connect('127.0.0.1', 6379);
   echo "Connection to server sucessfully";
   // Get the stored keys and print it
   $arList = $redis->keys("*");
   echo "Stored keys in redis:: "
   print_r($arList);
?>

當執行程序時,會產生下面的結果:


Connection to server sucessfully
Stored string in redis::
tutorial-name
tutorial-list


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM