PHP 中使用 Redis資料庫的例子

來源:互聯網
上載者:User


安裝

開始在 PHP 中使用 Redis 前, 我們需要確保已經安裝了 redis 服務及 PHP redis 驅動,且你的機器上能正常使用 PHP。 接下來讓我們安裝 PHP redis 驅動:下載地址為: https://github.com/phpredis/phpredis/releases 。

PHP安裝 redis 擴充

以下操作需要在下載的 phpredis 目錄中完成:

$ wget https://github.com/phpredis/phpredis/archive/2.2.4.tar.gz
$ cd phpredis-2.2.7                      # 進入 phpredis 目錄
$ /usr/local/php/bin/phpize              # php安裝後的路徑
$ ./configure --with-php-config=/usr/local/php/bin/php-config
$ make && make install
如果你是 PHP7 版本,則需要下載指定分支:

git clone -b php7 https://github.com/phpredis/phpredis.git
修改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 sucessfully
Server 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 sucessfully
Stored 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 sucessfully
Stored string in redis::
Redis
Mongodb
Mysql
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 sucessfully
Stored string in redis::
tutorial-name
tutorial-list

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.