Laravel5.3 combined with Workerman (asynchronous)
The following column workerman usage tutorial will introduce to you the method of using Laravel5.3 and Workerman together (asynchronously). I hope it will be helpful to friends in need!
Looking at the information online, there are ready-made composer components that are combined with Workerman, but I personally feel that they are not reliable. There are too few stars on github, and it is difficult to adjust if there are problems. I just wanted to try it myself first.
My method requires a little bit of Workerman source code to modify, and it directly introduces Workerman's code files, which feels a bit low, but my talent is limited and I haven't thought of a better method for the time being.
Preparation:
1. You need to understand the use of the command line under the Laravel framework. Please refer to the Chinese version of the tutorial
2. You need to understand the basic knowledge of Workerman
Scenario: After the user registers, send an email reminder to the user asynchronously
1. Place the Workerman framework in the app directory
2. Create the command code:
php artisan make:command SendEmail
namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; use Illuminate\Mail\Message; use Workerman\Worker; require app_path('Workerman/Workerman_Linux/Autoloader.php'); class SendEmail extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'send:email {action}'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * */ public function handle() { $mailWorker = new Worker('Text://0.0.0.0:12345'); $mailWorker->count = 4; $mailWorker->name = 'MailWorker'; $mailWorker->onMessage = function ($connection, $emailData) { $emailData = json_decode($emailData); $name = $emailData->name; $email = $emailData->to; Mail::raw('注册成功', function (Message $message) use ($email) { $message->to($email)->subject(trans('mail.welcome_register')); }); // 写入日志 Log::useFiles(storage_path() . '/logs/event.log', 'info'); Log::info("{$name}({$email})注册成功"); }; Worker::runAll(); } }
and above It is the workerman server. Start it with the command line:
php artisan send:email start
At this time, an error will be reported on the command line: Workerman[artisan] not run. The reason is that Workerman will use the first parameter artisan to start the current file. In fact, send:email is the startup file we want
Solution: Modify Workerman’s parsing parameter code
Workerman\Workerman_Linux\Worker.php, modify the parseCommand method (just change the keys of $argv Just add 1):
/** * Parse command. * php yourfile.php start | stop | restart | reload | status * * @return void */ protected static function parseCommand() { global $argv; if($argv[0] == 'artisan') // laravel框架下处理 { // Check argv; $start_file = $argv[1]; if (!isset($argv[2])) { exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n"); } // Get command. $command = trim($argv[2]); $command2 = isset($argv[3]) ? $argv[3] : ''; } else { // Check argv; $start_file = $argv[0]; if (!isset($argv[1])) { exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n"); } // Get command. $command = trim($argv[1]); $command2 = isset($argv[2]) ? $argv[2] : ''; } // 只要略修改上面的参数解析部分即可 .......................... }
Restart OK:
php artisan send:email start
3. The server is completed, the following is the client code
My email operation code is treated as an event logic, so write the code in the event listener file:
app\Listeners\SendMailEventListener.php:
<?php namespace App\Listeners; use App\Events\SendMailEvent;class SendMailEventListener extends BaseEventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SendMailEvent $event * @return void */ public function handle($event) { // 发送邮件通知注册成功 if ($event->user->scene == 'do_register') { $email = $event->user->email; //$ip = "mail_worker 的ip" ,本机的话为127.0.0.1 $socket = @stream_socket_client('tcp://127.0.0.1:12345', $errno, $errmsg, 5); if ($socket) { $mail_data = ['name'=>$event->user->name,'to' => $email, 'content' => trans('mail.welcome_register')]; // 注意,Text协议后面"\n"换行符是必须的 $mail_buffer = json_encode($mail_data) . "\n"; // 发送给mail worker fwrite($socket, $mail_buffer); } // $email = $event->user->email; // Mail::raw('注册成功',function (Message $message) use ($email) { // $message->to($email)->subject(trans('mail.welcome_register')); // }); } } }
4. Summary steps
Start the server---Register the user---Trigger the SendEmail event---socket client to the service Write data on the client---Send email on the server
Recommendation:Workerman Tutorial
The above is the detailed content of Laravel5.3 combined with Workerman (asynchronous). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to make PHP scripts run in the background by adding parameters -d? When writing PHP scripts, sometimes you need to have the script run in the background instead of occupying the foreground...

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...
