イントロダクションIntroduction
Redisは、オープンソースの高度なキー/値保存域です。文字列, ハッシュ, リスト, セット, and ソート済みセット.を含めることができるため、データ構造サーバと呼ばれることがあります。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によりphpredisPHP拡張機能をインストールして使用することを推奨します。この拡張機能は、「ユーザーフレンドリー」なPHPパッケージに比べてインストールは複雑ですが、Redisを多用するアプリケーションのパフォーマンスが向上する可能性があります。Laravel Sailを使用している場合、この拡張機能はアプリケーションのDockerコンテナにはじめからインストールしてあります。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 compared to "user-land" PHP packages but may yield better performance for applications that make heavy use of Redis. If you are using Laravel Sail[/docs/{{version}}/sail], this extension is already installed in your application's Docker container.
phpredis拡張機能をインストールできない場合は、Composerを介してpredis/predis
パッケージをインストールしてください。PredisはすべてPHPで記述されたRedisクライアントであり、追加の拡張機能は必要ありません。If you are unable to install the
phpredis extension, you may install the
predis/predis
package via Composer.
Predis is a Redis client written entirely in PHP and
does not require any additional
extensions:
composer require predis/predis
設定Configuration
config/database.php
設定ファイルによりアプリケーションのRedis設定を設定します。このファイル内に、アプリケーションで使用するRedisサーバを含むredis
配列があります。You may configure your
application's Redis settings via 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'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
'cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_CACHE_DB', 1),
],
],
設定ファイルで定義する各Redisサーバは、Redis接続を表す単一のURLを定義しない限り、名前、ホスト、およびポートを指定する必要があります。Each Redis server defined in your configuration file is required to have a name, host, and a 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クライアントはRedisサーバへ接続するとき、デフォルトでtcp
スキームを使用します。しかし、Redisサーバの設定配列でscheme
設定オプションを指定すれば、TLS/SSL暗号化を使用できます。By default, Redis clients will
use the tcp
scheme when connecting to
your Redis servers; however, you may use TLS / SSL
encryption by specifying a scheme
configuration option in your Redis server's
configuration array:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'scheme' => 'tls',
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
],
クラスタClusters
アプリケーションがRedisサーバのクラスタを利用する場合は、Redis設定のclusters
キー内で使用するクラスタを定義してください。この設定キーはデフォルトでは存在しないため、アプリケーションのconfig/database.php
設定ファイル内で作成する必要があります。If your application is utilizing
a cluster of Redis servers, you should define these
clusters within a clusters
key of your
Redis configuration. This configuration key does not
exist by default so you will need to create it
within your application's
config/database.php
configuration
file:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'clusters' => [
'default' => [
[
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
],
],
デフォルトでクラスタは、クライアント側のシャーディングをノード間で実行し、ノードをプールして大量の利用可能なRAMを作成できるようにします。ただし、クライアント側のシャーディングはフェイルオーバーを処理しません。したがって、これは主に、別のプライマリデータストアから利用できる一時的にキャッシュされたデータに適しています。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, client-side sharding does not handle failover; therefore, it is primarily suited for transient cached data that is available from another primary data store.
クライアント側のシャーディングの代わりにネイティブなRedisクラスタリングを使用する場合は、アプリケーションのconfig/database.php
設定ファイル内でoptions.cluster
設定値をredis
に設定してください。If you would like to use native
Redis clustering instead of client-side sharding,
you may specify this by setting the
options.cluster
configuration value to
redis
within your application's
config/database.php
configuration
file:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
],
'clusters' => [
// ...
],
],
PredisPredis
アプリケーションがPredisパッケージを介してRedisを操作するようにする場合は、REDIS_CLIENT
環境変数の値を確実にpredis
へ設定してください。If you would like your
application to interact with Redis via the Predis
package, you should ensure the
REDIS_CLIENT
environment variable's
value is predis
:
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
// ...
],
デフォルトの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 your
application's config/database.php
configuration file:
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
'read_write_timeout' => 60,
],
RedisファサードのエイリアスThe Redis Facade Alias
Laravelのconfig/app.php
設定ファイルにはaliases
配列があり、フレームワークが登録するすべてのクラスエイリアスを定義しています。デフォルトで、Redis
のエイリアスは含まれていません。なぜなら、phpredis拡張モジュールが提供するRedis
クラス名と衝突してしまうからです。Predisクライアントを使用していて、Redis
のエイリアスを追加したい場合は、アプリケーションのconfig/app.php
設定ファイル内のaliases
配列へ追加してください。Laravel's
config/app.php
configuration file
contains an aliases
array which defines
all of the class aliases that will be registered by
the framework. By default, no Redis
alias is included because it would conflict with the
Redis
class name provided by the
phpredis extension. If you are using the Predis
client and would like to add a Redis
alias, you may add it to the aliases
array in your application's
config/app.php
configuration
file:
'aliases' => Facade::defaultAliases()->merge([
'Redis' => Illuminate\Support\Facades\Redis::class,
])->toArray(),
phpredisphpredis
デフォルトでは、Laravelはphpredis拡張機能を使用してRedisと通信します。LaravelがRedisとの通信に使用するクライアントは、redis.client
設定オプションの値で決まります。これは通常、REDIS_CLIENT
環境変数の値を反映します。By default, Laravel will use the
phpredis extension to communicate with Redis. The
client that Laravel will use to communicate with
Redis is dictated by the value of the
redis.client
configuration option,
which typically reflects the value of the
REDIS_CLIENT
environment
variable:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
// 残りのRedis設定…
],
デフォルトのscheme
、host
、port
、database
、password
サーバ設定オプションに加えて、phpredisは次の追加の接続パラメータをサポートしています。name
、persistent
、persistent_id
、prefix
、read_timeout
、try_interval
、timeout
、context
です。config/database.php
設定ファイルのRedisサーバ設定へ、こうしたオプションを追加指定できます。In addition to the default
scheme
, host
,
port
, database
, and
password
server configuration options,
phpredis supports the following additional
connection parameters: name
,
persistent
, persistent_id
,
prefix
, read_timeout
,
retry_interval
, 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'),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
'read_timeout' => 60,
'context' => [
// 'auth' => ['username', 'secret'],
// 'stream' => ['verify_peer' => false],
],
],
phpredisのシリアライズと圧縮phpredis Serialization & Compression
phpredis拡張モジュールは、様々なシリアライズや圧縮アルゴリズムも設定できます。これらのアルゴリズムは、Redis設定のoptions
配列で指定します。The phpredis extension may also
be configured to use a variety of serialization and
compression algorithms. These algorithms can be
configured via the options
array of
your Redis configuration:
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'serializer' => Redis::SERIALIZER_MSGPACK,
'compression' => Redis::COMPRESSION_LZ4,
],
// 残りのRedis設定…
],
現在サポートしているシリアライズアルゴリズムは、Redis::SERIALIZER_NONE
(デフォルト)、Redis::SERIALIZER_PHP
、Redis::SERIALIZER_JSON
、Redis::SERIALIZER_IGBINARY
、Redis::SERIALIZER_MSGPACK
です。Currently supported serialization
algorithms include:
Redis::SERIALIZER_NONE
(default),
Redis::SERIALIZER_PHP
,
Redis::SERIALIZER_JSON
,
Redis::SERIALIZER_IGBINARY
, and
Redis::SERIALIZER_MSGPACK
.
サポートする圧縮アルゴリズムは、Redis::COMPRESSION_NONE
(デフォルト)、Redis::COMPRESSION_LZF
、Redis::COMPRESSION_ZSTD
、Redis::COMPRESSION_LZ4
です。Supported compression algorithms
include: Redis::COMPRESSION_NONE
(default), Redis::COMPRESSION_LZF
,
Redis::COMPRESSION_ZSTD
, and
Redis::COMPRESSION_LZ4
.
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 \Illuminate\Http\Response
*/
public function show($id)
{
return view('user.profile', [
'user' => Redis::get('user:profile:'.$id)
]);
}
}
上記のように、Redis
ファサードで任意のRedisコマンドを呼び出すことができます。Laravelはマジックメソッドを使用してコマンドをRedisサーバへ渡します。Redisコマンドが引数を必要とする場合は、それらをファサードの対応するメソッドへ渡す必要があります。As mentioned above, you may call
any of Redis' commands on the Redis
facade. Laravel uses magic methods to pass the
commands to the Redis server. If a Redis command
expects arguments, you should pass those to the
facade's corresponding method:
use Illuminate\Support\Facades\Redis;
Redis::set('name', 'Taylor');
$values = Redis::lrange('names', 5, 10);
または、Redis
ファサードのcommand
メソッドを使用してサーバにコマンドを渡すこともできます。このメソッドは、コマンドの名前を最初の引数、値の配列を2番目の引数に取ります。Alternatively, you may pass
commands to the server using the Redis
facade's 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
アプリケーションのconfig/database.php
設定ファイルでは、複数のRedis接続/サーバが定義できます。Redis
ファサードのconnection
メソッドを使用して、特定のRedis接続への接続を取得できます。Your application's
config/database.php
configuration file
allows you to define multiple Redis connections /
servers. You may obtain a connection to a specific
Redis connection using the Redis
facade's connection
method:
$redis = Redis::connection('connection-name');
デフォルトのRedis接続のインスタンスを取得するには、引数なしでconnection
メソッドを呼び出してください。To obtain an instance of the
default Redis connection, you may call the
connection
method without any
additional arguments:
$redis = Redis::connection();
トランザクションTransactions
Redis
ファサードのtransaction
メソッドは、RedisのネイティブMULTI
およびEXEC
コマンドの便利なラッパーを提供します。transaction
メソッドは、唯一の引数にクロージャを取ります。このクロージャはRedis接続インスタンスを受け取り、このインスタンスで必要なコマンドを発行できます。クロージャ内で発行したすべてのRedisコマンドは、単一のアトミックトランザクションとして実行します。The Redis
facade's
transaction
method provides a
convenient wrapper around Redis' native
MULTI
and EXEC
commands.
The transaction
method accepts a
closure as its only argument. This closure will
receive a Redis connection instance and may issue
any commands it would like to this instance. All of
the Redis commands issued within the closure will be
executed in a single, atomic transaction:
use Illuminate\Support\Facades\Redis;
Redis::transaction(function ($redis) {
$redis->incr('user_visits', 1);
$redis->incr('total_visits', 1);
});
Warning
Warning! Redisトランザクションを定義する場合、Redis接続から値を取得できません。トランザクションは単一のアトミック操作として実行し、クロージャ全体がコマンドの実行を完了するまで、操作は実行されないことに注意してください。
When defining a Redis transaction, you may not retrieve any values from the Redis connection. Remember, your transaction is executed as a single, atomic operation and that operation is not executed until your entire closure has finished executing its commands.
LuaスクリプトLua Scripts
eval
メソッドは、単一のアトミック操作で複数のRedisコマンドを実行する別のメソッドです。ただし、eval
メソッドには、その操作中にRedisキー/値を対話し調べられる利点があります。Redisスクリプトは、Luaプログラミング言語で記述します。The eval
method
provides another method of executing multiple Redis
commands in a single, atomic operation. However, the
eval
method has the benefit of being
able to interact with and inspect Redis key values
during that operation. Redis scripts are written in
the Lua programming
language[https://www.lua.org].
eval
メソッドは最初は少し怖いかもしれませんが、壁を超えるために基本的な例を見てみましょう。eval
メソッドは引数をいくつか取ります。まず、Luaスクリプトを(文字列として)メソッドへ渡す必要があります。次に、スクリプトが操作するキーの数を(整数として)渡す必要があります。第三に、それらのキーの名前を渡す必要があります。最後に、スクリプト内でアクセスする必要があるその他の追加の引数を渡します。The eval
method can
be a bit scary at first, but we'll explore a basic
example to break the ice. The eval
method expects several arguments. First, you should
pass the Lua script (as a string) to the method.
Secondly, you should pass the number of keys (as an
integer) that the script interacts with. Thirdly,
you should pass the names of those keys. Finally,
you may pass any other additional arguments that you
need to access within your script.
この例では、カウンターを増分し、その新しい値を検査し、最初のカウンターの値が5より大きい場合は、2番目のカウンターを増分します。最後に、最初のカウンターの値を返します。In this example, we will increment a counter, inspect its new value, and increment a second counter if the first counter's value is greater than five. Finally, we will return the value of the first counter:
$value = Redis::eval(<<<'LUA'
local counter = redis.call("incr", KEYS[1])
if counter > 5 then
redis.call("incr", KEYS[2])
end
return counter
LUA, 2, 'first-counter', 'second-counter');
Redisドキュメントを参照してください。Warning
Warning! Redisスクリプトの詳細には、
Please consult the Redis documentation[https://redis.io/commands/eval] for more information on Redis scripting.
パイプラインコマンドPipelining Commands
数十のRedisコマンドを実行する必要が起きることもあるでしょう。毎コマンドごとにRedisサーバへネットワークトリップする代わりに、pipeline
メソッドを使用できます。pipeline
メソッドは、Redisインスタンスを受け取るクロージャを1つ引数に取ります。このRedisインスタンスですべてのコマンドを発行すると、サーバへのネットワークトリップを減らすため、すべてのコマンドを一度にRedisサーバへ送信します。コマンドは、発行した順序で実行されます。Sometimes you may need to execute
dozens of Redis commands. Instead of making a
network trip to your Redis server for each command,
you may use the pipeline
method. 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 sent to the Redis server at the
same time to reduce network trips to the server. The
commands will still be executed in the order they
were issued:
use Illuminate\Support\Facades\Redis;
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i ) {
$pipe->set("key:$i", $i);
}
});
Pub/SubPub / 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
メソッドを使用してチャンネルリスナを設定しましょう。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
{
/**
* consoleコマンドの名前と使用方法
*
* @var string
*/
protected $signature = 'redis:subscribe';
/**
* コンソールコマンドの説明
*
* @var string
*/
protected $description = 'Subscribe to a Redis channel';
/**
* consoleコマンドの実行
*
* @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:
use Illuminate\Support\Facades\Redis;
Route::get('/publish', function () {
// ...
Redis::publish('test-channel', json_encode([
'name' => 'Adam Wathan'
]));
});
ワイルドカードサブスクリプションWildcard Subscriptions
psubscribe
メソッドを使用すると、ワイルドカードチャンネルをサブスクライブできます。これは、すべてのチャンネルのすべてのメッセージをキャッチするのに役立ちます。チャンネル名は、引数に渡たすクロージャの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 closure:
Redis::psubscribe(['*'], function ($message, $channel) {
echo $message;
});
Redis::psubscribe(['users.*'], function ($message, $channel) {
echo $message;
});