Introducer
Before writing Event/listener For instance, the data is directly stored, and this step can be put into the queue to execute. The laravel queue has multiple drivers to choose from, and redis is used here.
Create queue
- Using php artisan make:job BrowseLogQueue, you can create a queue file and eventually generate a Jobs/BrowseLogQueue.php file.
- The function is just data warehousing, and the code is very simple. Note that configurations such as maximum number of failures can be specified in the class, as follows
<?php /** * Browse Records to Store */ namespace App\Jobs; use App\Events\NotifyAdmin; use App\Models\BrowseLog; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Exception; class BrowseLogQueue implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; // Maximum number of failures public $tries = 5; // overtime public $timeout = 120; protected $ip_addr; protected $request_url; protected $city_name; protected $created_at; protected $updated_at; /** * Create a new job instance. * * @return void */ public function __construct($ip_addr, $request_url, $city_name, $now) { $this->ip_addr = $ip_addr; $this->request_url = $request_url; $this->city_name = $city_name; $this->created_at = $now; $this->updated_at = $now; } /** * Execute the job. * * @return void */ public function handle(BrowseLog $browseLog) { $log = new $browseLog; $log->ip_addr = $this->ip_addr; $log->request_url = $this->request_url; $log->city_name = $this->city_name; $log->created_at = $this->created_at; $log->updated_at = $this->updated_at; $log->save(); } /** * Mission failure * @param Exception $exception */ public function failed(Exception $exception) { // Send an email to inform the administrator event(new NotifyAdmin($exception->getMessage())); } }
Distribution task
Modify the listener CreateBrowseLog.php file as follows
/** * Handle the event. * * @param UserBrowse $event * @return void */ public function handle(UserBrowse $event) { // Local access is not recorded $arr = ['127.0.0.1']; if (!in_array($event->ip_addr, $arr)) { /*$log = new \App\Models\BrowseLog(); $log->ip_addr = $event->ip_addr; $log->request_url = $event->request_url; $log->city_name = $event->city_name; $log->save();*/ BrowseLogQueue::dispatch($event->ip_addr, $event->request_url, $event->city_name, now()); /*BrowseLogQueue::dispatch($event->ip_addr, $event->request_url, $event->city_name)->delay(now()->addMinute(1)); Delayed addition */ } }
Run queue
The last step is to run the queue and execute php artisan queue:work.
There's no problem running, but it's not over yet. You need to use the Supervisor process guardian, and continue with the next article.
Reference material: queue.