ホームページ  >  記事  >  php教程  >  Redis PHP接続操作

Redis PHP接続操作

WBOY
WBOYオリジナル
2016-06-16 08:39:28957ブラウズ

インストール

PHP プログラムで Redis を使用するには、まず Redis 用の PHP ドライバーと PHP インストールがマシン上にセットアップされていることを確認する必要があります。 PHP チュートリアルを参照して、マシンに PHP をインストールする方法を学ぶことができます。次に、Redis 用の PHP ドライバーのセットアップを見てみましょう。

phpredis を github リポジトリ (https://github.com/nicolasff/phpredis) からダウンロードする必要があります。ダウンロードが完了したら、ファイルを phpredis ディレクトリに解凍します。この拡張機能を Ubuntu にインストールするには、次の図に示すコマンドを使用してインストールします。

<span class="pln">
cd phpredis
sudo phpize
sudo ./configure
sudo make
sudo make install

</span>

次に、「modules」フォルダーの内容をコピーして PHP 拡張機能ディレクトリに貼り付け、php.ini に次の行を追加します。

<span class="pln">
extension = redis.so

</span>

これで、Redis と PHP のインストールが完了しました。

Redis サーバーに接続します

<span class="pln">
<?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();
?>

</span>

プログラムが実行されると、次の結果が生成されます:

<span class="pln">
Connection to server sucessfully
Server is running: PONG

</span>

Redis PHP 文字列の例

<span class="pln">
<?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");
?>

</span>

プログラムが実行されると、次の結果が生成されます:

<span class="pln">
Connection to server sucessfully
Stored string in redis:: Redis tutorial

</span>

Redis PHP リストの例

<span class="pln">
<?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);
?>

</span>

プログラムが実行されると、次の結果が生成されます:

<span class="pln">
Connection to server sucessfully
Stored string in redis::
Redis
Mongodb
Mysql

</span>

Redis PHP キーの例

<span class="pln">
<?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);
?>

</span>

プログラムが実行されると、次の結果が生成されます:

<span class="pln">
Connection to server sucessfully
Stored string in redis::
tutorial-name
tutorial-list</span>
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。