Readouble

Laravel 4.2 キュー

設定Configuration

Laravelのキューコンポーネントは様々なキューサービスに共通のAPIを提供しています。キューによりメール送信のような時間を費やす処理を夜中まで遅らせることが可能です。これによりアプリケーションのリクエストを徹底的に引き上げることができます。The Laravel Queue component provides a unified API across a variety of different queue services. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time, thus drastically speeding up the web requests to your application.

キュー設定ファイルはapp/config/queue.phpです。このファイルには、フレームワークに含まれているそれぞれのドライバーへの接続設定があります。それには、BeanstalkdIronMQAmazon SQSRedis、synchronous(同期ドライバー、ローカルでの使用)ドライバーが含まれています。The queue configuration file is stored in app/config/queue.php. In this file you will find connection configurations for each of the queue drivers that are included with the framework, which includes a Beanstalkd[http://kr.github.com/beanstalkd], IronMQ[http://iron.io], Amazon SQS[http://aws.amazon.com/sqs], Redis[http://redis.io], and synchronous (for local use) driver.

前記のキュードライバーを使用するには、以下の対応するパッケージをcomposer.jsonに付け加えることが必要です。The following dependencies are needed for the listed queue drivers:

  • Beanstalkd: pda/pheanstalk ~2.0Beanstalkd: pda/pheanstalk ~2.0
  • Amazon SQS: aws/aws-sdk-phpAmazon SQS: aws/aws-sdk-php
  • IronMQ: iron-io/iron_mqIronMQ: iron-io/iron_mq

基本的な使用法Basic Usage

キューにジョブを登録するPushing A Job Onto The Queue

新しいジョブをキューに入れるには`Queue::push'メソッドを使います。To push a new job onto the queue, use the Queue::push method:

Queue::push('SendEmail', array('message' => $message));

ジョブハンドラーを定義するDefining A Job Handler

pushメソッドの最初の引数は、ジョブを処理するクラス名です。2番目はハンドラーに渡すデーターの配列です。ハンドラは以下のように定義します。The first argument given to the push method is the name of the class that should be used to process the job. The second argument is an array of data that should be passed to the handler. A job handler should be defined like so:

class SendEmail {

	public function fire($job, $data)
	{
		//
	}

}

キューに登録されたデーターの配列と共に、ジョブのインスタンスを受け取るための、fireメソッドが最低必要であることに注意してください。Notice the only method that is required is fire, which receives a Job instance as well as the array of data that was pushed onto the queue.

カスタムハンドラーメソッドを指定するSpecifying A Custom Handler Method

もしfire以外のメソッドで処理したい場合は、登録するジョブにメソッドも指定してください。If you want the job to use a method other than fire, you may specify the method when you push the job:

Queue::push('SendEmail@send', array('message' => $message));

ジョブにキュー/チューブを指定するSpecifying The Queue / Tube For A Job

どのキュー/チューブにジョブを登録するのかを指定することもできます。You may also specify the queue / tube a job should be sent to:

Queue::push('SendEmail@send', array('message' => $message), 'emails');

同じペイロードを複数のジョブに渡すPassing The Same Payload To Multiple Jobs

同じデーターを複数のキュージョブに送る必要がある場合は、Queue::bulkメソッドを使用して下さい。If you need to pass the same data to several queue jobs, you may use the Queue::bulk method:

Queue::bulk(array('SendEmail', 'NotifyUser'), $payload);

ジョブの実行を遅らせるDelaying The Execution Of A Job

場合によってはキュージョブの実行を遅らせたいこともあるでしょう。例えば、サインアップの15分後に顧客へメールを送信するジョブをキューしたい場合です。この場合、Queue::latorメソッドを使用して下さい。Sometimes you may wish to delay the execution of a queued job. For instance, you may wish to queue a job that sends a customer an e-mail 15 minutes after sign-up. You can accomplish this using the Queue::later method:

$date = Carbon::now()->addMinutes(15);

Queue::later($date, 'SendEmail@send', array('message' => $message));

この例の中で、ジョブに希望する遅延実行時間を指定するために、Carbonライブラリーを使用しています。もしくは、整数で遅らせたい秒数を渡すこともできます。In this example, we're using the Carbon[https://github.com/briannesbitt/Carbon] date library to specify the delay we wish to assign to the job. Alternatively, you may pass the number of seconds you wish to delay as an integer.

注目: Amazon SQSサービスの場合、遅延は900秒(15分)の制限があります。Note: The Amazon SQS service has a delay limit of 900 seconds (15 minutes).

処理済みのジョブを削除するDeleting A Processed Job

あるジョブを処理したら、それはキューから削除されなくてはなりません。ジョブインスタンスのdeleteメソッドでこれを行います。Once you have processed a job, it must be deleted from the queue, which can be done via the delete method on the Job instance:

public function fire($job, $data)
{
	// Process the job...

	$job->delete();
}

キューに再登録するReleasing A Job Back Onto The Queue

もしジョブを再実行するため、ジョブに登録し直すのであれば、releaseメソッドを使用してください。If you wish to release a job back onto the queue, you may do so via the release method:

public function fire($job, $data)
{
	// Process the job...

	$job->release();
}

そのジョブが再実行されるまでの間隔を秒で指定することもできます。You may also specify the number of seconds to wait before the job is released:

$job->release(5);

実行回数を調べるChecking The Number Of Run Attempts

ジョブの処理中に例外が起きた場合、そのジョブは自動的にキューに再登録されます。そのジョブを実行しようとした試行回数をattemptsメソッドで調べることができます。If an exception occurs while the job is being processed, it will automatically be released back onto the queue. You may check the number of attempts that have been made to run the job using the attempts method:

if ($job->attempts() > 3)
{
	//
}

ジョブIDにアクセスするAccessing The Job ID

ジョブ識別子にもアクセスできます。You may also access the job identifier:

$job->getJobId();

クロージャーのキューQueueing Closures

もしくはキューにクロージャーを登録することも可能です。これは手軽にシンプルなタスクをキュー登録する必要がある場合に大変便利です。You may also push a Closure onto the queue. This is very convenient for quick, simple tasks that need to be queued:

キューにクロージャーを登録するPushing A Closure Onto The Queue

Queue::push(function($job) use ($id)
{
	Account::delete($id);

	$job->delete();
});

注目: useを通じてキューするクロージャーでオブジェクトを使用できるようにする代わりに、主キーを渡し、キュージョブの中で関連するモデルを再取得することを考慮してください。これにより、予期しないシリアライズの影響を防ぐことができます。Note: Instead of making objects available to queued Closures via the use directive, consider passing primary keys and re-pulling the associated models from within your queue job. This often avoids unexpected serialization behavior.

Iron.ioのPushキューを利用する場合、キューのクロージャーで追加の予防策を取る必要があります。キューメッセージを受け取った時点でそのキューが本当にIron.ioからのリクエストであるかをチェックしてください。例えば、Pushキューの受け取りURLをhttps:://yourapp.com/queue/receive?token=秘密のトークンのような形式で登録します。次に、キューリクエストでmarshalメソッドを実行する前に、秘密のトークンの値をアプリケーションでチェックします。When using Iron.io push queues[#push-queues], you should take extra precaution queueing Closures. The end-point that receives your queue messages should check for a token to verify that the request is actually from Iron.io. For example, your push queue end-point should be something like: https://yourapp.com/queue/receive?token=SecretToken. You may then check the value of the secret token in your application before marshalling the queue request.

キューリスナーの実行Running The Queue Listener

LaravelのArtisanは、新しくキューに保存されたジョブを実行するコマンドを含んでいます。`queue:listen'コマンドで、このタスクを実行できます。Laravel includes an Artisan task that will run new jobs as they are pushed onto the queue. You may run this task using the queue:listen command:

キューリスナーを開始するStarting The Queue Listener

php artisan queue:listen

リスナーに使用するキュー接続を指定することもできます。You may also specify which queue connection the listener should utilize:

php artisan queue:listen connection

このタスクを一度開始したら、手動で停止しない限り実行を続けることに注意してください。Supervisorのようなプロセスモニターを利用し、キューリスナーが確実に動作し続けるようにしてください。Note that once this task has started, it will continue to run until it is manually stopped. You may use a process monitor such as Supervisor[http://supervisord.org/] to ensure that the queue listener does not stop running.

listenコマンドにキューのプライオリティーを設定するため、キュー接続をカンマ区切りで指定することもできます。You may pass a comma-delimited list of queue connections to the listen command to set queue priorities:

php artisan queue:listen --queue=high,low

この例で、high-connectionlow-connectionのジョブを実行する前にいつも処理されます。In this example, jobs on the high-connection will always be processed before moving onto jobs from the low-connection.

ジョブのタイムアウト時間を指定するSpecifying The Job Timeout Parameter

それぞれのジョブの実行時間を秒数で指定することもできます。You may also set the length of time (in seconds) each job should be allowed to run:

php artisan queue:listen --timeout=60

キューのスリープ時間を指定するSpecifying Queue Sleep Duration

さらに、新しいジョブをポーリングする前に、待ち秒数を指定することもできます。In addition, you may specify the number of seconds to wait before polling for new jobs:

php artisan queue:listen --sleep=5

キューにジョブがない場合のみ、キューがスリープすることに注意して下さい。もし、ジョブが存在しているなら、キューはスリープせずに処理を続けます。Note that the queue only "sleeps" if no jobs are on the queue. If more jobs are available, the queue will continue to work them without sleeping.

キューの最初のジョブを実行するProcessing The First Job On The Queue

キューの最初のジョブだけを実行するには、queue:workコマンドを使用してください。To process only the first job on the queue, you may use the queue:work command:

php artisan queue:work

デーモン・キュー・ワーカーDaemon Queue Worker

queue:workは更に、フレームワークを再起動せずとも連続してジョブを処理し続けるように、キューワーカーを強制するための、--daemonオプションを持っています。これにより、queue:listenと比較すると、CPU使用率を大幅に引き下げることができますが、デプロイ中は現在実行中のジョブのキューを空にするために、複雑な手順の追加が必要になります。The queue:work also includes a --daemon option for forcing the queue worker to continue processing jobs without ever re-booting the framework. This results in a significant reduction of CPU usage when compared to the queue:listen command, but at the added complexity of needing to drain the queues of currently executing jobs during your deployments.

キュー・ワーカーをデーモンモードで開始するためには、--daemonフラッグを使用します。To start a queue worker in daemon mode, use the --daemon flag:

php artisan queue:work connection --daemon

php artisan queue:work connection --daemon --sleep=3

php artisan queue:work connection --daemon --sleep=3 --tries=3

ご覧の通り、queue:workコマンドはqueue:listenで使用できるものと、ほとんど同じオプションをサポートしています。php artisan help queue:workコマンドで全オプションを表示できます。As you can see, the queue:work command supports most of the same options available to queue:listen. You may use the php artisan help queue:work command to view all of the available options.

デーモン・キュー・ワーカーでデプロイするDeploying With Daemon Queue Workers

アプリケーションをデーモン・キュー・ワーカーでデプロイする、一番簡単な方法は、デプロイを開始するときに、アプリケーションをメンテナンスモードにすることです。これはphp artisan downコマンドで切り替えられます。アプリケーションをメンテナンスモードにしたら、Laravelは新しいジョブをキューに受け付けなくなりますが、存在しているジョブの処理は続けます。The simplest way to deploy an application using daemon queue workers is to put the application in maintenance mode at the beginning of your deployment. This can be done using the php artisan down command. Once the application is in maintenance mode, Laravel will not accept any new jobs off of the queue, but will continue to process existing jobs.

ワーカーを一番簡単に再起動するには、デプロイスクリプトの中に、次のコマンドを含めてください。The easiest way to restart your workers is to include the following command in your deployment script:

php artisan queue:restart

このコマンドは、現在のジョブの処理が終了した後、全キューワーカーを再起動するように指示します。This command will instruct all queue workers to restart after they finish processing their current job.

注意: このコマンドは再起動のスケジュールするため、キャッシュシステムを利用しています。デフォルト状態では、APCuはCLIコマンドのために動作しません。APCuを使用する場合、apc.enable_cli=1をAPCu設定に追加してください。Note: This command relies on the cache system to schedule the restart. By default, APCu does not work for CLI commands. If you are using APCu, add apc.enable_cli=1 to your APCu configuration.

デーモンキューワーカーのコーディングCoding For Daemon Queue Workers

デーモンキューワーカーは、各ジョブを処理する前にフレームワークを再起動しません。そのため、多くのリソースを使用するジョブを完了する前に、それらを開放するように気をつけてください。例えば、GDライブラリーを使用し、画像処理を行う場合、完了したらimagedestroyでメモリを開放する必要があるでしょう。Daemon queue workers do not restart the framework before processing each job. Therefore, you should be careful to free any heavy resources before your job finishes. For example, if you are doing image manipulation with the GD library, you should free the memory with imagedestroy when you are done.

同様に、長時間動作するデーモンに使用されると、データベース接続は切断されるでしょう。新しい接続を行うために、DB::reconnectメソッドを使う必要が起きるでしょう。Similarly, your database connection may disconnect when being used by long-running daemon. You may use the DB::reconnect method to ensure you have a fresh connection.

PushキューPush Queues

Pushキューでデーモンやバックグラウンドリスナーを走らせなくてもLaravel4のキュー機能を存分に利用できます。現在、PushキューはIron.ioドライバーでしかサポートされていません。開始する前にIron.ioのアカウントを作成し、Ironの認証データーをapp/config/queus.php設定ファイルに追加してください。Push queues allow you to utilize the powerful Laravel 4 queue facilities without running any daemons or background listeners. Currently, push queues are only supported by the Iron.io[http://iron.io] driver. Before getting started, create an Iron.io account, and add your Iron credentials to the app/config/queue.php configuration file.

Pushキューの購読を登録するRegistering A Push Queue Subscriber

次に、新しく登録されたキュージョブを受け取るエンドポイントURLをqueue::subscribe Artisanコマンドで登録します。Next, you may use the queue:subscribe Artisan command to register a URL end-point that will receive newly pushed queue jobs:

php artisan queue:subscribe queue_name http://foo.com/queue/receive

これでIronダッシュボードへログインすると、新しいPushキューが購読URLと共に表示されます。指定したキューに対し、好きなだけURLを購読することもできます。次に、queue/receiveエンドポイントへのルートを生成し、Queue::marshalメソッドからのレスポンスをリターンしてください。Now, when you login to your Iron dashboard, you will see your new push queue, as well as the subscribed URL. You may subscribe as many URLs as you wish to a given queue. Next, create a route for your queue/receive end-point and return the response from the Queue::marshal method:

Route::post('queue/receive', function()
{
	return Queue::marshal();
});

marshalメソッドは正しいジョブハンドラークラスが実行されるように取り計らいます。Pushキューへのジョブを実行するには、Queue::pushメソッドと同様にキューの使用手順に従い利用してください。The marshal method will take care of firing the correct job handler class. To fire jobs onto the push queue, just use the same Queue::push method used for conventional queues.

失敗したジョブFailed Jobs

物事はうまく行かない場合もありますから、キュージョブが失敗することもあるでしょう。心配ありません。最高な人たちも失敗はするのです!Laravelは指定した回数ジョブを再実行する便利な方法を用意しています。この回数実行してもうまく行かない場合は、faild_jobsテーブルに登録されます。この失敗したジョブのテーブル名は、app/config/queue.php設定ファイルで指定できます。Since things don't always go as planned, sometimes your queued jobs will fail. Don't worry, it happens to the best of us! Laravel includes a convenient way to specify the maximum number of times a job should be attempted. After a job has exceeded this amount of attempts, it will be inserted into a failed_jobs table. The failed jobs table name can be configured via the app/config/queue.php configuration file.

faild_jobsテーブルのマイグレーションを生成するには、queue:faild-tableコマンドを実行して下さい。To create a migration for the failed_jobs table, you may use the queue:failed-table command:

php artisan queue:failed-table

ジョブ再実行の最大回数を指定するには、queue:listenコマンドに--triesスイッチを付け実行して下さい。You can specify the maximum number of times a job should be attempted using the --tries switch on the queue:listen command:

php artisan queue:listen connection-name --tries=3

キュージョブが失敗した時に呼び出されるイベントのリスナーを登録したい場合は、Queue::failingメソッドを使って下さい。このイベントは、メールかHipChatであなたのチームに通知するために便利でしょう。If you would like to register an event that will be called when a queue job fails, you may use the Queue::failing method. This event is a great opportunity to notify your team via e-mail or HipChat[https://www.hipchat.com].

Queue::failing(function($connection, $job, $data)
{
	//
});

失敗したジョブを全部確認するには、queue:failed Arisanコマンドを利用します。To view all of your failed jobs, you may use the queue:failed Artisan command:

php artisan queue:failed

queue:failedコマンドにジョブIDを指定すれば、接続、キュ、失敗した時間がリストされます。ジョブIDは失敗したジョブを再実行する場合にも使用します。例えば、IDが5の失敗したジョブを再実行するには、以下のコマンドを実行します。The queue:failed command will list the job ID, connection, queue, and failure time. The job ID may be used to retry the failed job. For instance, to retry a failed job that has an ID of 5, the following command should be issued:

php artisan queue:retry 5

失敗したジョブを削除するには、queue:forgetコマンドを使います。If you would like to delete a failed job, you may use the queue:forget command:

php artisan queue:forget 5

失敗したジョブを全部消去するには、queue:flushコマンドを使用します。To delete all of your failed jobs, you may use the queue:flush command:

php artisan queue:flush

章選択

Artisan CLI

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作