Laravel

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 your config/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のpublishsubscribeコマンドの便利なインターフェイスも提供しています。これらの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;
});

ドキュメント章別ページ

開発環境
ビューとテンプレート
Artisanコンソール
公式パッケージ

ヘッダー項目移動

注目:アイコン:ページ内リンク設置(リンクがないヘッダーへの移動では、リンクがある以前のヘッダーのハッシュをURLへ付加します。

移動

クリックで即時移動します。

設定

適用ボタンクリック後に、全項目まとめて適用されます。

カラーテーマ
和文指定 Pagination
和文指定 Scaffold
Largeスクリーン表示幅
インデント
本文フォント
コードフォント
フォント適用確認

フォントの指定フィールドから、フォーカスが外れると、当ブロックの内容に反映されます。EnglishのDisplayもPreviewしてください。

フォント設定時、表示に不具合が出た場合、当サイトのクッキーを削除してください。

バックスラッシュを含むインライン\Code\Blockの例です。

以下はコードブロックの例です。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ユーザに関連する電話レコードを取得
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

設定を保存する前に、表示が乱れないか必ず確認してください。CSSによるフォントファミリー指定の知識がない場合は、フォントを変更しないほうが良いでしょう。

キーボード・ショートカット

オープン操作

PDC

ページ(章)移動の左オフキャンバスオープン

HA

ヘッダー移動モーダルオープン

MS

移動/設定の右オフキャンバスオープン

ヘッダー移動

T

最初のヘッダーへ移動

E

最後のヘッダーへ移動

NJ

次ヘッダー(H2〜H4)へ移動

BK

前ヘッダー(H2〜H4)へ移動

その他

?

このヘルプページ表示
閉じる