Home PHP Framework ThinkPHP Think-Swoole Task asynchronous task

Think-Swoole Task asynchronous task

Oct 27, 2020 pm 01:39 PM
think-swoole

Think-Swoole Task asynchronous task

Usage scenarios

If you need to perform a time-consuming operation in the Server program, such as a chat server sending Broadcast, send emails from the web server. If you directly execute these functions, the current process will be blocked, causing the server to respond slowly. For example: In the user registration scenario, the function of completing registration and sending activation emails requires the following steps:

The client submits POST data -> The server obtains the data -> Completes the registration and writes the user data to the database - > Send account activation email-> Return to the client to prompt that the registration is successful.

There is no problem with this business logic, but sending an email is a time-consuming operation (such as 2-3s) and will synchronously block the execution of the program until the client is prompted to register successfully after the sending is successful. In this process, it is estimated that it takes about 4 seconds from submission to the final notification of successful registration. A request response takes 4 seconds, which is definitely unreasonable!

Now using Task asynchronous task delivery can greatly improve the user experience. The general process is:

The client submits POST data-> The server obtains the data-> Completes the registration and writes the user data to the database -> Immediately return to the client to prompt that the registration is successful.

Deliver a Task task when the registration is successful -> Complete the time-consuming operation of sending the email asynchronously (the user is unaware of this part of the time, because the response has been returned to the client very early).

How to use Think-Swoole's Task asynchronous task steps

Define event listening class (php think make:listener class name).

The event monitoring of swoole.task is defined in the app/event.php file.

Get the Swoole/Server object and call the task method (pass the listening class just defined in the parameter).

Define the trigger callback logic code in the handle method of the event listening class just defined.

Call the finish method that triggers task swoole.finish after the task is completed (called only when needed, not required).

Demo

First, create an email sending event in the project root directory:

php think make:listener EmailTask
Copy after login

Then define the created email sending event:

app/event.php
'listen'    => [
    'AppInit'  => [],
    'HttpRun'  => [],
    'HttpEnd'  => [],
    'LogLevel' => [],
    'LogWrite' => [],
    'swoole.task' => [
        app\listener\EmailTask::class,
    ],
//  'swoole.finish' => [
//      app\listener\EmailTaskFinish::class,
//  ],
],
Copy after login

The key name of swoole.task is Task. Tasks are written in a fixed way and cannot be named arbitrarily.

Next, we call the Task asynchronous task through the Swoole/Server class in the controller responsible for user registration. Of course, we must first improve the logic code of EmailTask.php:

app/ listener/EmailTask.php

<?php
declare (strict_types = 1);
namespace app\listener;
class EmailTask
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event)
{
        echo "开始发送邮件:".time();
        //模拟耗时 3 秒,测试是否在响应事件内
        sleep(3);
        echo "邮件发送成功:".time();
        // 可以调用 finish 方法通知其他事件类,通知当前异步任务已经完成了(非必须调用)
        // 参数 $event 是 Swoole\Server\Task 类的一个对象 可以调用 finish 方法触发 task 任务的 onFinish 事件
        // $event -> finish(\app\listener\EmailTaskFinish::class);
    }
}
Copy after login

Registration method app/controller/Register.php

<?php
namespace app\controller;
use app\BaseController;
class Register extends BaseController
{
    public function register(\Swoole\Server $server)
{
        if($this -> request -> isPost()){
            $data = $this -> request -> post();
            //TODO 调用验证类验证数据
            //TODO 将注册信息插入数据库
            // 这里调用 Task 异步任务
            $server -> task(\app\listener\EmailTask::class);
            // 方式二
//            $manager = app(&#39;\think\swoole\Manager&#39;);
//            $manager -> getServer() -> task(\app\listener\EmailTask::class);
            return "注册成功!".time();
        }
    }
}
Copy after login

In the registration business, after inserting into the database, the asynchronous task of sending emails is called, and the email is simulated in EmailTask.php It takes 3 seconds.

Open the Think-Swoole service, access the registration method, and test whether the time for sending emails is included in the user registration method:

Think-Swoole Task asynchronous task

Visible, the email is sent The 3 seconds are performed asynchronously and the user is not aware of it.

In addition, there is a swoole.finish event, which is used to notify other events that the current asynchronous task has been completed. You also need to create an event and define swoole.finish in app/event.php. The above sample code has been demonstrated .

The above is the detailed content of Think-Swoole Task asynchronous task. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Performance optimization and debugging of TP6 Think-Swoole RPC service Performance optimization and debugging of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:16 AM

Performance optimization and debugging of TP6Think-SwooleRPC service 1. Introduction With the rapid development of the Internet, distributed computing has become an indispensable part of modern software development. In distributed computing, RPC (RemoteProcedureCall, Remote Procedure Call) is a commonly used communication mechanism through which method calls across the network can be implemented. Think-Swoole, as a high-performance PHP framework, can support RPC services well. but

High scalability and distributed deployment of TP6 Think-Swoole RPC service High scalability and distributed deployment of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:07 AM

TP6 (ThinkPHP6) is an open source framework based on PHP, which has the characteristics of high scalability and distributed deployment. This article will introduce how to use TP6 with Swoole extension to build a highly scalable RPC service, and give specific code examples. First, we need to install TP6 and Swoole extensions. Execute the following command in the command line: composerrequiretopthink/thinkpeclinstallswo

Data encryption and identity authentication mechanism of TP6 Think-Swoole RPC service Data encryption and identity authentication mechanism of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:29 AM

Data encryption and identity authentication mechanism of TP6Think-SwooleRPC service With the rapid development of the Internet, more and more applications need to make remote calls to realize data interaction and function calls between different modules. In this context, RPC (RemoteProcedureCall) has become an important communication method. The TP6Think-Swoole framework can implement high-performance RPC services. This article will introduce how to use data encryption and identity authentication.

Highly concurrent request processing and scheduling of TP6 Think-Swoole RPC service Highly concurrent request processing and scheduling of TP6 Think-Swoole RPC service Oct 12, 2023 pm 12:33 PM

Highly concurrent request processing and scheduling of TP6Think-SwooleRPC service With the continuous development of Internet technology, concurrent request processing and scheduling of network applications has become an important challenge. In the TP6 framework, the Think-Swoole extension can be used to implement high-concurrency request processing and scheduling of the RPC (RemoteProcedureCall) service. This article will introduce how to build a Think-Swoole-based RPC service in the TP6 framework and provide

Security protection and authorization verification of TP6 Think-Swoole RPC service Security protection and authorization verification of TP6 Think-Swoole RPC service Oct 12, 2023 pm 01:15 PM

Security protection and authorization verification of TP6Think-SwooleRPC service With the rise of cloud computing and microservices, remote procedure call (RPC) has become an essential part of developers' daily work. When developing RPC services, security protection and authorization verification are very important to ensure that only legitimate requests can access and call the service. This article will introduce how to implement security protection and authorization verification of RPC services in the TP6Think-Swoole framework. 1. Basic concepts of RPC services

TP6 Think-Swoole's RPC service and message queue integration and application TP6 Think-Swoole's RPC service and message queue integration and application Oct 12, 2023 am 11:37 AM

Integration and application of TP6Think-Swoole's RPC service and message queue In modern software development, RPC service (RemoteProcedureCall) and message queue are common technical means used to implement service calls and asynchronous message processing in distributed systems. Integrating Think-Swoole components in the TP6 framework can easily implement the functions of RPC services and message queues, and provides concise code examples for developers to understand and apply. 1. RPC

Performance testing and performance tuning of TP6 Think-Swoole RPC service Performance testing and performance tuning of TP6 Think-Swoole RPC service Oct 12, 2023 pm 02:19 PM

Performance testing and performance tuning of TP6Think-SwooleRPC service 1. Introduction With the rapid development of the Internet, the application of distributed systems is becoming more and more widespread. In distributed systems, RPC (Remote Procedure Call) is a common communication mechanism, which allows services on different nodes to call each other and achieve collaborative work in distributed systems. In the TP6 framework, Think-Swoole, as a high-performance Swoole driver, provides convenient RPC service support. This article mainly introduces T

TP6 RPC service and microservice architecture practice cases built by Think-Swoole TP6 RPC service and microservice architecture practice cases built by Think-Swoole Oct 12, 2023 pm 12:04 PM

Introduction to the practical case of RPC service and microservice architecture built by TP6Think-Swoole: With the rapid development of the Internet and the expansion of business scale, the traditional monolithic architecture can no longer meet the needs of large-scale business scenarios. Therefore, the microservice architecture came into being. In the microservice architecture, the RPC (RemoteProcedureCall) service is an important way to achieve communication between services. Through RPC services, various microservices can call each other conveniently and efficiently. In this article

See all articles