イントロダクションIntroduction
Redisはオープンソースの進歩的なキー/値保存システムです。キーに文字列、ハッシュ、リスト、セット、ソート済みセットが使用できるため、データ構造サーバとしてよく名前が上がります。Redis[https://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[https://redis.io/topics/data-types#strings], hashes[https://redis.io/topics/data-types#hashes], lists[https://redis.io/topics/data-types#lists], sets[https://redis.io/topics/data-types#sets], and sorted sets[https://redis.io/topics/data-types#sorted-sets].
LaravelでRedis使用するには、PECLを使用してPhpRedis PHP拡張をインストールすることを推奨します。インストール方法は複雑ですが、Redisをヘビーユースするアプリケーションではより良いパフォーマンスが得られますBefore using Redis with Laravel, we encourage you to install and use the PhpRedis[https://github.com/phpredis/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.
もしくは、Composerでpredis/predis
パッケージをインストールすることもできます。Alternatively, you can install
the predis/predis
package via
Composer:
composer require predis/predis
設定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 utilized by your
application:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
'cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_CACHE_DB', 1),
],
],
デフォルトのサーバ設定は、開発時には十分でしょう。しかしご自由に自分の環境に合わせてこの配列を変更してください。Redis接続を表すシングルURLを定義していない場合、各Redisサーバの名前、ホスト、ポートの指定が必要です。The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Each Redis server defined in your configuration file is required to have a name, host, and port unless you define a single URL to represent the Redis connection:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'url' => 'tcp://127.0.0.1:6379?database=0',
],
'cache' => [
'url' => 'tls://user:password@127.0.0.1:6380?database=1',
],
],
接続スキームの設定Configuring The Connection Scheme
デフォルトでRedisサーバへの接続に、tcp
スキームをRedisクライアントは使用します。しかし、Redisサーバ接続設定のscheme
設定オプションを指定すれば、TLS/SSL暗号化を使用できます。By default, Redis clients will
use the tcp
scheme when connecting to
your Reids servers; however, you may use TLS / SSL
encryption by specifying a scheme
configuration option in your Redis server
configuration:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'scheme' => 'tls',
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
],
クラスタ設定Configuring Clusters
アプリケーションでRedisサーバのクラスタを使用している場合は、Redis設定のclusters
キーで定義する必要があります。If your application is utilizing
a cluster of Redis servers, you should define these
clusters within a clusters
key of your
Redis configuration:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'clusters' => [
'default' => [
[
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
],
],
デフォルトでクラスタはノード間のクライアントサイドシェアリングを実行し、ノードをプールし、利用可能な大きいRAMを作成できるようにします。しかしながら、クライアントサイドシェアリングはフェイルオーバーを処理しません。そのため、他のプライマリデータ保存域からのキャッシュデータを使用できるようにするため適しています。ネイティブなRedisクラスタリングを使用したい場合は、Redis設置のoptions
キーでこれを指定してください。By default, clusters will perform
client-side sharding across your 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. If you would like to use native
Redis clustering, you should specify this in the
options
key of your Redis
configuration:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
],
'clusters' => [
// ...
],
],
PredisPredis
Predis拡張を使用するには、REDIS_CLIENT
環境変数をphpredis
からpredis
へ変更します。To utilize the Predis extension,
you should change the REDIS_CLIENT
environment variable from phpredis
to
predis
:
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
// 残りのRedis設定…
],
デフォルトのhost
、port
、database
、password
オプションに加え、Predisは各Redisサーバに対する接続パラメータを定義する機能をサポートしています。これらの追加設定オプションを使うには、config/database.php
設定ファイルのRedisサーバ設定へ追加してください。In addition to the default
host
, port
,
database
, and password
server configuration options, Predis supports
additional connection
parameters[https://github.com/nrk/predis/wiki/Connection-Parameters]
that may be defined for each of your Redis servers.
To utilize these additional configuration options,
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,
],
PhpRedisPhpRedis
PhpRedis拡張は、config/database.php
の中でREDIS_CLIENT
環境変数のデフォルトとして設定されています。The PhpRedis extension is
configured as default at REDIS_CLIENT
env and in your
config/database.php
:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
// 残りのRedis設定…
],
Redis
ファサードエイリアスに加えPhpRedis拡張を使用する予定であれば、Redisクラスとの衝突を避けるために、RedisManager
のような他の名前にリネームする必要があります。app.php`設定ファイルのエイリアスセクションで行えます。If you plan to use PhpRedis
extension along with the Redis
Facade
alias, you should rename it to something else, like
RedisManager
, to avoid a collision with
the Redis class. You can do that in the aliases
section of your app.php
config
file.
'RedisManager' => Illuminate\Support\Facades\Redis::class,
デフォルトのhost
、port
、database
、password
オプションに加え、PhpRedisはpersistent
、prefix
、read_timeout
、timeout
、context
追加オプションをサポートしています。config/database.php
設定ファイル中のRedisサーバ設定に、これらのオプションを追加してください。In addition to the default
host
, port
,
database
, and password
server configuration options, PhpRedis supports the
following additional connection parameters:
persistent
, prefix
,
read_timeout
, timeout
, and
context
. 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,
'context' => [
// 'auth' => ['username', 'secret'],
// 'stream' => ['verify_peer' => false],
],
],
RedisファサードThe Redis Facade
Redis
PHP拡張自身と名前が衝突するのを避けるため、app
設定ファイルのaliases
配列からIlluminate\Support\Facades\Redis
ファサードエイリアスを削除かリネームする必要があります。一般的には、このエイリアスを完全に取り除き、Redis
PHP拡張を使用するときに完全なクラス名を指定することで、ファサードを参照するに留めるべきです。To avoid class naming collisions
with the Redis PHP extension itself, you will need
to delete or rename the
Illuminate\Support\Facades\Redis
facade
alias from your app
configuration
file's aliases
array. Generally, you
should remove this alias entirely and only reference
the facade by its fully qualified class name while
using the Redis PHP extension.
Redisの操作Interacting With Redis
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[https://redis.io/commands] on the
facade and the command will be passed directly to
Redis. In this example, we will call the Redis
GET
command by calling the
get
method on the Redis
facade:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
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コマンドで期待されている引数を渡してください。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 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サーバのインスタンスが取得できます。さらに、Redis設定で定義した、特定のサーバやクラスタを取得するために、connection
メソッドへ接続名やクラスタ名を渡すこともできます。This will give you an instance of
the default Redis server. You may also pass the
connection or cluster name to the
connection
method to get a specific
server or cluster as defined in your Redis
configuration:
$redis = Redis::connection('my-connection');
パイプラインコマンドPipelining Commands
サーバに対し多くのコマンドを送る必要がある場合はパイプラインを使うべきでしょう。pipeline
メソッドは引数をひとつだけ取り、Redisインスタンスを取る「クロージャ」です。このRedisインスタンスは全コマンドをサーバへストリーミングするので、良いパフォーマンスが得られます。Pipelining should be used when
you need to send many commands to the server. 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 streamed to the server
thus providing better performance:
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i ) {
$pipe->set("key:$i", $i);
}
});
publish/subscribePub / Sub
さらにLaravelは、Redisのpublish
とsubscribe
コマンドの便利なインターフェイスも提供しています。これらのRedisコマンドは、指定した「チャンネル」のメッセージをリッスンできるようにしてくれます。他のアプリケーションからこのチャンネルにメッセージを公開するか、他の言語を使うこともでき、これによりアプリケーション/プロセス間で簡単に通信できます。Laravel 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 and
processes.
最初にsubscribe
メソッドでRedisを経由するチャンネルのリスナを準備します。subscribe
メソッドは長時間動作するプロセスですので、このメソッドはArtisanコマンドの中で呼び出します。First, let's setup a channel
listener using the subscribe
method.
We'll 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 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
メソッドを使いチャンネルへメッセージを公開できます。Now we may publish messages to
the channel using the publish
method:
Route::get('publish', function () {
// Route logic...
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 may be 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;
});