イントロダクションIntroduction
Redisはオープンソースの進歩的なキー/値保存システムです。キーに文字列、ハッシュ、リスト、セット、ソート済みセットが使用できるため、データ構造サーバーとしてよく名前が上がります。LaravelでRedisを使う前にpredis/predis
パッケージ(~1.0)をComposerでインストールしておく必要があります。Redis[http://redis.io] is
an open source, advanced key-value store. It is
often referred to as a data structure server since
keys can contain
strings[http://redis.io/topics/data-types#strings],
hashes[http://redis.io/topics/data-types#hashes],
lists[http://redis.io/topics/data-types#lists],
sets[http://redis.io/topics/data-types#sets],
and sorted
sets[http://redis.io/topics/data-types#sorted-sets].
Before using Redis with Laravel, you will need to
install the predis/predis
package
(~1.0) via Composer.
設定Configuration
アプリケーションのRedis設定はconfig/database.php
ファイルにあります。このファイルの中にredis
配列があり、アプリケーションで使用されるRadisサーバーの設定を含んでいます。The Redis configuration for your
application is located in the
config/database.php
configuration file.
Within this file, you will see a redis
array containing the Redis servers used by your
application:
'redis' => [
'cluster' => false,
'default' => [
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
],
],
デフォルトのサーバー設定は、開発時には十分でしょう。しかしご自由に自分の環境に合わせてこの配列を変更してください。各Redisサーバーに名前を与え、使用するホストとポートを指定するだけです。The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Simply give each Redis server a name, and specify the host and port used by the server.
ノードをプールしたり、巨大なRAMを使用可能にしたりするため、cluster
オプションはRedisノード間に渡りクライアントサイドで共有する指示をLaravel
Redisクライアントに対し行います。しかし注意すべきはクライアントサイドの共有ではフェイルオーバーが処理されないことです。そのため主な使い方は、他のプライマリーのデーター域からキャッシュデーターを使用できるようにすることでしょう。The cluster
option
will tell the Laravel Redis client to perform
client-side sharding across your Redis nodes,
allowing you to pool nodes and create a large amount
of available RAM. However, note that client-side
sharding does not handle failover; therefore, is
primarily suited for cached data that is available
from another primary data store.
Redis接続の定義の中でoptions
配列値を定義することも追加で可能で、Predisクライアントオプションの設定を指定できます。Additionally, you may define an
options
array value in your Redis
connection definition, allowing you to specify a set
of Predis client
options[https://github.com/nrk/predis/wiki/Client-Options].
Redisサーバーが認証を求めている場合、Redisサーバー設定のpassword
オプションへキー/値のペアを指定してください。If your Redis server requires
authentication, you may supply a password by adding
a password
configuration item to your
Redis server configuration array.
注意: PECLでRedis PHP拡張をインストールしている場合、
config/app.php
ファイルのRedisエイリアスをリネームする必要があります。Note: If you have the Redis PHP extension installed via PECL, you will need to rename the alias for Redis in yourconfig/app.php
file.
基本的な使用法Basic Usage
Redis
ファサードのバラエティー豊かなメソッドを呼び出し、Redisを操作できます。Redis
ファサードは動的メソッドをサポートしています。つまりファサードでどんなRedisコマンドでも呼び出すことができ、そのコマンドは直接Redisへ渡されます。以下の例ではRedisのGET
コマンドをRedis
ファサードのget
メソッドで呼び出しています。You may interact with Redis by
calling various methods on the Redis
facade[/docs/{{version}}/facades]. The
Redis
facade supports dynamic methods,
meaning you may call any Redis
command[http://redis.io/commands] on the
facade and the command will be passed directly to
Redis. In this example, we will call the
GET
command on Redis by calling the
get
method on the Redis
facade:
<?php
namespace App\Http\Controllers;
use 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コマンドで期待されている引数を渡してください。Of course, as mentioned above,
you may call any of the Redis commands on the
Redis
facade. Laravel uses magic
methods to pass the commands to the Redis server, so
simply pass the arguments the Redis command
expects:
Redis::set('name', 'Taylor');
$values = Redis::lrange('names', 5, 10);
サーバーにコマンドを送る別の方法はcommand
メソッドを使う方法です。最初の引数にコマンド名、第2引数に値の配列を渡します。Alternatively, you may also pass
commands to the server using the
command
method, which accepts the name
of the command as its first argument, and an array
of values as its second argument:
$values = Redis::command('lrange', ['name', 5, 10]);
複数のRedis接続の使用Using Multiple Redis Connections
RedisインスタンスをRedis::connection
メソッドの呼び出しで取得できます。You may get a Redis instance by
calling the Redis::connection
method:
$redis = Redis::connection();
これによりデフォルトのRedisサーバーのインスタンスが取得されます。サーバークラスタリングを使用していない場合、connection
メソッドにサーバー名を指定することで、Redis設定で定義している特定のサーバーを取得できます。This will give you an instance of
the default Redis server. If you are not using
server clustering, you may pass the server name to
the connection
method to get a specific
server as defined in your Redis
configuration:
$redis = Redis::connection('other');
パイプラインコマンドPipelining Commands
一回の操作でサーバーに対し多くのコマンドを送る必要がある場合はパイプラインを使うべきでしょう。pipeline
メソッドは引数をひとつだけ取り、Redisインスタンスを取る「クロージャー」です。このRedisインスタンスで全コマンドを発行し、一回の操作で全部実行できます。Pipelining should be used when
you need to send many commands to the server in one
operation. The pipeline
method accepts
one argument: a Closure
that receives a
Redis instance. You may issue all of your commands
to this Redis instance and they will all be executed
within a single operation:
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i ) {
$pipe->set("key:$i", $i);
}
});
発行/購読Pub / Sub
さらにLaravelはRedisのpublish
とsubscribe
コマンドの便利なインターフェイスも提供しています。これらのRedisコマンドは指定した「チャンネル」のメッセージをリッスンできるようにしてくれます。他のアプリケーションからこのチャンネルにメッセージを公開するか、他の言語を使うこともでき、これによりアプリケーション/プロセス間で簡単に通信できます。Laravel also provides a
convenient interface to the Redis
publish
and subscribe
commands. These Redis commands allow you to listen
for messages on a given "channel". You may
publish messages to the channel from another
application, or even using another programming
language, allowing easy communication between
applications / processes.
最初にsubscribe
メソッドでRedisを経由するチャンネルのリスナーを準備します。subscribe
メソッドは長時間動作するプロセスを開始しますので、このメソッドはArtisanコマンドの中で呼び出します。First, let's setup a listener on
a channel via Redis using the subscribe
method. We will place this method call within an
Artisan command[/docs/{{version}}/artisan]
since calling the subscribe
method
begins a long-running process:
<?php
namespace App\Console\Commands;
use Redis;
use Illuminate\Console\Command;
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
メソッドを使いチャンネルへメッセージを公開できます。Now, we may publish messages to
the channel using the publish
method:
Route::get('publish', function () {
// ルートのロジック
Redis::publish('test-channel', json_encode(['foo' => 'bar']));
});
ワイルドカード購入Wildcard Subscriptions
psubscribe
メソッドでワイルドカードチャネルに対し購入できます。全チャンネルの全メッセージを補足するために便利です。$channel
名は指定するコールバックの第2引数として渡されます。Using the psubscribe
method, you may subscribe to a wildcard channel,
which is useful for catching all messages on all
channels. The $channel
name will be
passed as the second argument to the provided
callback Closure
:
Redis::psubscribe(['*'], function($message, $channel) {
echo $message;
});
Redis::psubscribe(['users.*'], function($message, $channel) {
echo $message;
});