Redis
イントロダクション
Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets.
Before using Redis with Laravel, you will either need to install the
predis/predis
package via Composer:
composer require predis/predis
Alternatively, you may install the PhpRedis PHP extension via PECL. The extension is more complex to install but may yield better performance for applications that make heavy use of Redis.
設定
アプリケーションのRedis設定はconfig/database.php
ファイルにあります。このファイルの中にredis
配列があり、アプリケーションで使用されるRadisサーバーの設定を含んでいます。
'redis' => [
'client' => 'predis',
'cluster' => false,
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
デフォルトのサーバー設定は、開発時には十分でしょう。しかしご自由に自分の環境に合わせてこの配列を変更してください。各Redisサーバーは名前、ホスト、ポートの指定が必要です。
ノードをプールしたり、巨大なRAMを使用可能にしたりするため、cluster
オプションは、Redisノード間に渡りクライアントサイドで共有する指示をLaravel
Redisクライアントに対し行います。しかし、注意すべきはクライアントサイドの共有では、フェイルオーバーが処理されないことです。そのため、主な使い方は他のプライマリーのデーター域から、キャッシュデーターを使用できるようにすることでしょう。
Predis
In addition to the default host
, port
,
database
, and password
server configuration
options, Predis supports additional connection
parameters that may be defined for each of your Redis servers. To
utilize these additional configuration options, simply add them to your
Redis server configuration in the config/database.php
configuration file:
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
'read_write_timeout' => 60,
],
PhpRedis
Note: If you have the PhpRedis PHP extension installed via PECL, you will need to rename the
Redis
alias in yourconfig/app.php
configuration file.
To utilize the PhpRedix extension, you should change the
client
option of your Redis configuration to
phpredis
. This option is found in your
config/database.php
configuration file:
'redis' => [
'client' => 'phpredis',
// Rest of Redis configuration...
],
In addition to the default host
, port
,
database
, and password
server configuration
options, PhpRedis supports the following additional connection
parameters: persistent
, prefix
,
read_timeout
and timeout
. You may add any of
these options to your Redis server configuration in the
config/database.php
configuration file:
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
'read_timeout' => 60,
],
Redisの操作
Redis
ファサードのバラエティー豊かなメソッドを呼び出し、Redisを操作できます。Redis
ファサードは動的メソッドをサポートしています。つまりファサードでどんなRedisコマンドでも呼び出すことができ、そのコマンドは直接Redisへ渡されます。以下の例ではRedisのGET
コマンドをRedis
ファサードのget
メソッドで呼び出しています。
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* 指定ユーザーのプロフィール表示
*
* @param int $id
* @return Response
*/
public function showProfile($id)
{
$user = Redis::get('user:profile:'.$id);
return view('user.profile', ['user' => $user]);
}
}
もちろん前記の通り、Redis
ファサードでどんなRedisコマンドでも呼び出すことができます。Laravelはmagicメソッドを使いコマンドをRedisサーバーへ送りますので、Redisコマンドで期待されている引数を渡してください。
Redis::set('name', 'Taylor');
$values = Redis::lrange('names', 5, 10);
サーバーにコマンドを送る別の方法はcommand
メソッドを使う方法です。最初の引数にコマンド名、第2引数に値の配列を渡します。
$values = Redis::command('lrange', ['name', 5, 10]);
複数のRedis接続の使用
RedisインスタンスをRedis::connection
メソッドの呼び出しで取得できます。
$redis = Redis::connection();
これによりデフォルトのRedisサーバーのインスタンスが取得されます。サーバークラスタリングを使用していない場合、connection
メソッドにサーバー名を指定することで、Redis設定で定義している特定のサーバーを取得できます。
$redis = Redis::connection('other');
パイプラインコマンド
一回の操作でサーバーに対し多くのコマンドを送る必要がある場合はパイプラインを使うべきでしょう。pipeline
メソッドは引数をひとつだけ取り、Redisインスタンスを取る「クロージャ」です。このRedisインスタンスで全コマンドを発行し、一回の操作で全部実行できます。
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", $i);
}
});
publish/subscribe
さらにLaravelは、Redisのpublish
とsubscribe
コマンドの便利なインターフェイスも提供しています。これらのRedisコマンドは、指定した「チャンネル」のメッセージをリッスンできるようにしてくれます。他のアプリケーションからこのチャンネルにメッセージを公開するか、他の言語を使うこともでき、これによりアプリケーション/プロセス間で簡単に通信できます。
最初にsubscribe
メソッドでRedisを経由するチャンネルのリスナを準備します。subscribe
メソッドは長時間動作するプロセスですので、このメソッドはArtisanコマンドの中で呼び出します。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class RedisSubscribe extends Command
{
/**
* コンソールコマンドの名前と使用法
*
* @var string
*/
protected $signature = 'redis:subscribe';
/**
* コンソールコマンドの説明
*
* @var string
*/
protected $description = 'Subscribe to a Redis channel';
/**
* コンソールコマンドの実行
*
* @return mixed
*/
public function handle()
{
Redis::subscribe(['test-channel'], function($message) {
echo $message;
});
}
}
これでpublish
メソッドを使いチャンネルへメッセージを公開できます。
Route::get('publish', function () {
// Route logic...
Redis::publish('test-channel', json_encode(['foo' => 'bar']));
});
ワイルドカード購入
psubscribe
メソッドでワイルドカードチャネルに対し購入できます。全チャンネルの全メッセージを補足するために便利です。$channel
名は指定するコールバック「クロージャ」の第2引数として渡されます。
Redis::psubscribe(['*'], function($message, $channel) {
echo $message;
});
Redis::psubscribe(['users.*'], function($message, $channel) {
echo $message;
});