Laravel 队列

新建任务
namespace App\Jobs;

use app\Models\postArticle;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class PostArticle implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $postArticle;

    /**
     * 创建一个新的任务实例。
     *
     * @param  postArticle $postArticle
     * @return void
     */
    public function __construct(postArticle $postArticle)
    {
        $this->postArticle= $postArticle;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        // Process post work...
    }
}

分发任务
namespace App\Http\Controllers;

use App\Jobs\PostArticle;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * 
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // 发布文章...
        
		// 参数将被传递给 Jobs的 __construct()
        PostArticle::dispatch($postArticle);

		// 延迟分发
		//  PostArticle::dispatch($postArticle)->delay(now()->addMinutes(10));
		
		// 同步执行
		//  PostArticle::dispatchNow($postArticle);

		//工作链
//工作链允许你具体定义一个按序列执行队列任务的列表。一旦序列中的任务失败了,剩余的工作将不会执行。要运行
//一个工作链,你可以对可分发的任务使用 withChain 方法:

		PostArticle::withChain([
		    new AJob,
		    new BJob
		])->dispatch()->allOnConnection('redis')->allOnQueue('postArticle');
		
		// 指定连接  指定队列  【也可以联合起来用】
		//  PostArticle::dispatch($postArticle)->onConnection('redis');
		//  PostArticle::dispatch($postArticle)->onQueue('job1');
    }
}

任务事件
通过在 Queue facade 中使用 before 和 after 方法,你可以指定一个队列任务被执行前后的回调。这些回调是添加额外的日志或增加统计的绝好时机。通常,你应该在 服务提供者中调用这些方法。
例如,我们可以使用 Laravel 的 AppServiceProvider
class AppServiceProvider extends ServiceProvider
{
    /**
     * 引导启动任意应用服务。
     *
     * @return void
     */
    public function boot()
    {
        Queue::before(function (JobProcessing $event) {
            // $event->connectionName
            // $event->job
            // $event->job->payload()
        });

        Queue::after(function (JobProcessed $event) {
            // $event->connectionName
            // $event->job
            // $event->job->payload()
        });
    }

    /**
     * 注册服务提供者。
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<div class="post-text" itemprop="text"> <p>I have an array containing about ~8,000 stock tickers that I'm trying to queue up; the queue is meant to receive the array of stock tickers ($symbols[]), and then pass each one to a worker / consumer (whichever jargon you prefer). </p> <p>Here's what my QueueController current looks like:</p> <pre><code>Class QueueController extends \BaseController { public function stocks() { $symbols = $this->select_symbols(); Queue::push('StockQueue', array('symbols' => $symbols)); } ... } </code></pre> <p>From my QueueController, I'm calling a method to retrieve the list of stock symbols and passing it to the StockQueue Class as the $data.</p> <pre><code>public function fire($job, $data) { $symbols = $data; // print_r shows all symbols... // Get Quote Data for Symbol $quote = $this->yql_get_quote($symbol); // Get Key Stats for Symbol $keystats = $this->yql_get_keystats($symbol); // Merge Quote and Keystats into an Array $array[] = $quote; $array[] = $keystats; // Save Data to DB $this->yql_save_results($array, $symbol); $job->delete(); } </code></pre> <p>This is not what I'm trying to achieve though; what I need to do is pass in each symbol, one by one, to the StockQueue Class, and have it process it as a task.</p> <p>If I were to wrap the StockQueue->stocks() method in a while loop, it would try and pass all ~8,000 in (from what I understand) immediately to the queue. Would this be detrimental or is this the best way to do it? I haven't been able to find a lot of examples for PHP-based RPC Message Queuing online, so I'm just as curious about the best practices as I am on the correct process.</p> <p>With that being said, how can I fire up multiple workers for this queue? Say, I want 5 workers (depending on how many resources each one takes; I'll figure that out) to process these tasks in order to reduce the processing time by ~4/5ths. How would I do that?</p> <p>Would I just launch <code>php artisan queue:listen</code> five times?</p> <p>And, for clarity, I'm using beanstalkd and supervisord to do the message queue / monitoring.</p> <p>I look forward to your advice and insight. </p> </div>
<div class="post-text" itemprop="text"> <p>In Laravel I have a Controller like this:</p> <pre><code><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Database\Eloquent\Model; use App\Dienstreise; class DienstreiseController extends Controller { public static function store() { $dienstreise = new Dienstreise; $dienstreise->user_id=1; $dienstreise->start_ort = "Hamburg"; $dienstreise->ziel_ort = "Kassel"; $dienstreise->save(); return "OK"; } } </code></pre> <p>I have a route for that function, that works totally fine. (So the database-settings are 100% correct)</p> <pre><code>Route::get('/dienstreise', 'DienstreiseController@store'); </code></pre> <p>But now I have a file in a folder in my public-folder, which needs to access that function in the controller too. (I know that sounds strange, but the file will get a POST Request from Dialogflow and so the file must be located in the public folder, otherwise they can't access it)</p> <p>The file looks like this:</p> <pre><code><?php require __DIR__ . '/../../vendor/autoload.php'; use App\Http\Controllers\DienstreiseController; use Illuminate\Http\Request; use Illuminate\Database\Eloquent\Model; use App\Dienstreise; $dr = DienstreiseController::store(); echo $dr; ?> </code></pre> <p>But I get a 500-HTTP-Error? The log:</p> <p><code>PHP Fatal error: Uncaught Error: Call to a member function connection() on null in /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1140</code></p> <p>If I comment all the lines with $dienstreise... in the controller, I get the "OK", so the mistake must be there... But why does it work with the route? I'm confused. I read about uncommenting "$app->withEloquent();" in bootstrap/app.php, but there is nothing like this commented? </p> </div>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页