Home PHP Framework Workerman Laravel5.3 combined with Workerman (asynchronous)

Laravel5.3 combined with Workerman (asynchronous)

Nov 25, 2019 pm 05:11 PM
laravel workerman

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!

Laravel5.3 combined with Workerman (asynchronous)

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
Copy after login
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();
    }
}
Copy after login

and above It is the workerman server. Start it with the command line:

php artisan send:email start
Copy after login
Copy after login

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] : '';
        }
    
     // 只要略修改上面的参数解析部分即可 
     ..........................
}
Copy after login

Restart OK:

php artisan send:email start
Copy after login
Copy after login

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:
Copy after login
<?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 == &#39;do_register&#39;) {
            $email = $event->user->email;

            //$ip = "mail_worker 的ip" ,本机的话为127.0.0.1
            $socket = @stream_socket_client(&#39;tcp://127.0.0.1:12345&#39;, $errno, $errmsg, 5);
            if ($socket) {
                $mail_data = [&#39;name&#39;=>$event->user->name,&#39;to&#39; => $email, &#39;content&#39; => trans(&#39;mail.welcome_register&#39;)];
                // 注意,Text协议后面"\n"换行符是必须的
                $mail_buffer = json_encode($mail_data) . "\n";
                // 发送给mail worker
                fwrite($socket, $mail_buffer);
            }

//            $email = $event->user->email;
//            Mail::raw(&#39;注册成功&#39;,function (Message $message) use ($email) {
//                $message->to($email)->subject(trans(&#39;mail.welcome_register&#39;));
//            });
        }
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

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 custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

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

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

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...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

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,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

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 script run in the background by adding parameters -d? How to make PHP script run in the background by adding parameters -d? Apr 01, 2025 pm 02:27 PM

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 effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

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...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

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...

See all articles