Home PHP Framework Swoole Swoole asynchronous programming practice: creating a high-performance queuing system

Swoole asynchronous programming practice: creating a high-performance queuing system

Jun 13, 2023 am 09:11 AM
high performance Asynchronous programming swoole

With the rapid development of Internet applications, more and more companies are beginning to use asynchronous programming to improve code performance and application efficiency. Swoole is a powerful asynchronous programming framework for PHP, with high performance, high concurrency and excellent scalability. In this article, we will introduce how to use Swoole to build a high-performance queuing system.

First of all, we need to understand what a queuing system is. The queuing system is a service overall scheduling system that improves the response speed of services and the concurrent processing capabilities of the system by queuing management and scheduling of various services. In practical applications, queuing systems are usually used to implement functions such as high concurrent access, asynchronous task scheduling, load balancing, etc. Therefore, their high performance and high availability are necessary.

Next, we will use the following requirements as an example to explain how to use Swoole to build a high-performance queuing system:

  1. Supports multiple queues and can manage queues ;
  2. Supports the addition and execution of tasks, and can manage the status of tasks;
  3. Supports multiple consumers to process tasks, and can manage consumers;
  4. Support task retry and timeout processing;
  5. Support asynchronous processing and synchronous processing of tasks.

Now, let’s get down to business and start using Swoole to build this high-performance queuing system.

1. Introducing Swoole

First of all, we need to introduce Swoole into the project. Here we can easily introduce Swoole dependencies through Composer.

composer require swoole/swoole

2. Build queue

In the queuing system, the queue is the core structure for storing tasks. We need to build a queue and add tasks to the queue. Here we use Redis as the queue storage method and use the PHP Redis extension to operate the queue.

  1. Create Redis connection

Before using Redis, we need to create a connection with Redis first. Here we create a Redis connection pool to manage Redis connections.

use SwooleCoroutineChannel;

class RedisPool
{

private $max;
private $pool;

public function __construct($max = 100)
{
    $this->max = $max;
    $this->pool = new Channel($max);
}

public function get($config)
{
    if (!$this->pool->isEmpty()) {
        return $this->pool->pop();
    }

    $redis = new Redis();
    $redis->connect($config['host'], $config['port']);
    $redis->select($config['db']);
    
    return $redis;
}

public function put($redis)
{
    if ($this->pool->length() < $this->max) {
        $this->pool->push($redis);
    } else {
        $redis->close();
    }
}
Copy after login

}

  1. Create Queue

Connect Next, we can create a queue class to manage queue operations, including task addition, task acquisition, and task deletion.

class Queue
{

private $redis;

public function __construct($config)
{
    $this->redis = (new RedisPool())->get($config);
}

public function push($queueName, $data)
{
    $this->redis->lpush($queueName, $data);
}

public function pop($queueName)
{
    return $this->redis->rpop($queueName);
}

public function del($queueName, $data)
{
    $this->redis->lrem($queueName, -1, $data);
}
Copy after login

}

3. Implement task execution

After adding a task to the queue, we need a task executor to perform tasks. Here we use coroutines to implement asynchronous execution of tasks, and use Worker processes to improve task execution efficiency.

  1. Create Worker process

In Swoole, we can use Worker process to implement multi-process processing tasks. Here we create a Worker process to handle the task.

$worker = new SwooleProcessWorker();

  1. Create a coroutine executor

Next, we can create a coroutine executor to handle Task. Here we use coroutines to implement asynchronous task execution, and use Golang-style coroutine pools to improve the efficiency of concurrent processing.

class CoroutineExecutor
{

private $pool;
private $redisConfig;

public function __construct($maxCoroutineNum, $redisConfig)
{
    $this->pool = new SwooleCoroutineChannel($maxCoroutineNum);
    $this->redisConfig = $redisConfig;

    for ($i = 0; $i < $maxCoroutineNum; $i++) {
        $this->pool->push(new Coroutine());
    }
}

public function execute($callback, $data)
{
    $coroutine = $this->pool->pop();
    $coroutine->execute($callback, $data, $this->redisConfig);
    $this->pool->push($coroutine);
}
Copy after login

}

  1. Creating a coroutine

Next, we can create a coroutine to perform tasks.

class Coroutine
{

private $redis;

public function __construct()
{
    $this->redis = null;
}

public function execute($callback, $data, $config)
{
    if (!$this->redis) {
        $this->redis = (new RedisPool())->get($config);
    }
    
    Coroutine::create(function () use ($callback, $data) {
        call_user_func($callback, $this->redis, $data);
    });
}
Copy after login

}

4. Create a service

Finally, we can use Swoole to create a service to provide queue query and Functionality added by tasks.

  1. Implement queue management

We can use Swoole's HTTP Server to implement service port monitoring and perform queue management through HTTP requests. Here we provide interfaces for list acquisition, task deletion and task addition.

  1. Realize task execution

We can use Swoole's TaskWorker process to implement task execution. By dispatching tasks to the TaskWorker process, the TaskWorker process executes the tasks asynchronously.

class Task
{

public function execute($worker, $workerId, $taskId, $taskData)
{
    $executor = new CoroutineExecutor(64, [
        'host' => '127.0.0.1',
        'port' => 6379,
        'db' => 0
    ]);
    $executor->execute($taskData['callback'], $taskData['data']);

    return true;
}
Copy after login

}

  1. Implement service startup

Finally, we can implement service startup and monitoring port, and start the TaskWorker process to perform the task.

$http = new SwooleHttpServer("127.0.0.1", 9501);
$http->on('start', function () {

echo "Server started
Copy after login

";
});

$http->on('request', function ($request, $response) {

$queue = new Queue([
    'host' => '127.0.0.1',
    'port' => 6379,
    'db' => 0
]);

switch ($request->server['request_uri']) {
    case '/queue/list':
        // 获取队列列表
        break;
    case '/queue/delete':
        // 删除任务
        break;
    case '/queue/add':
        $data = json_decode($request->rawContent(), true);
        $queue->push($data['queue'], $data['data']);
        $http->task([
            'callback' => function ($redis, $data) {
                // 任务执行逻辑
            },
            'data' => $data
        ]);
        break;
    default:
        $response->status(404);
        $response->end();
        break;
}
Copy after login

});

$http-> ;on('task', function ($http, $taskId, $workerId, $data) {

$task = new Task();
$result = $task->execute($http, $workerId, $taskId, $data);

return $result;
Copy after login

});

$http->on('finish', function ($http, $taskId, $data) {

// 任务执行完成逻辑
Copy after login

});

$http->start();

5. Summary

This article introduces how to use Swoole to implement a high-performance queuing system. Through Swoole's coroutines and Worker processes, we can achieve high-performance processing of asynchronous tasks, and achieve efficient task management and scheduling through the Redis storage structure. Such a queuing system can be widely used in functional scenarios such as asynchronous task scheduling, high concurrent access, load balancing, etc. It is a solution worthy of promotion and use.

The above is the detailed content of Swoole asynchronous programming practice: creating a high-performance queuing system. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 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)

How to implement asynchronous programming with C++ functions? How to implement asynchronous programming with C++ functions? Apr 27, 2024 pm 09:09 PM

Summary: Asynchronous programming in C++ allows multitasking without waiting for time-consuming operations. Use function pointers to create pointers to functions. The callback function is called when the asynchronous operation completes. Libraries such as boost::asio provide asynchronous programming support. The practical case demonstrates how to use function pointers and boost::asio to implement asynchronous network requests.

How to use swoole coroutine in laravel How to use swoole coroutine in laravel Apr 09, 2024 pm 06:48 PM

Using Swoole coroutines in Laravel can process a large number of requests concurrently. The advantages include: Concurrent processing: allows multiple requests to be processed at the same time. High performance: Based on the Linux epoll event mechanism, it processes requests efficiently. Low resource consumption: requires fewer server resources. Easy to integrate: Seamless integration with Laravel framework, simple to use.

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

How does swoole_process allow users to switch? How does swoole_process allow users to switch? Apr 09, 2024 pm 06:21 PM

Swoole Process allows users to switch. The specific steps are: create a process; set the process user; start the process.

Which one has better performance, swoole or java? Which one has better performance, swoole or java? Apr 09, 2024 pm 07:03 PM

Performance comparison: Throughput: Swoole has higher throughput thanks to its coroutine mechanism. Latency: Swoole's coroutine context switching has lower overhead and smaller latency. Memory consumption: Swoole's coroutines occupy less memory. Ease of use: Swoole provides an easier-to-use concurrent programming API.

How to restart the service in swoole framework How to restart the service in swoole framework Apr 09, 2024 pm 06:15 PM

To restart the Swoole service, follow these steps: Check the service status and get the PID. Use "kill -15 PID" to stop the service. Restart the service using the same command that was used to start the service.

Common problems and solutions in asynchronous programming in Java framework Common problems and solutions in asynchronous programming in Java framework Jun 04, 2024 pm 05:09 PM

3 common problems and solutions in asynchronous programming in Java frameworks: Callback Hell: Use Promise or CompletableFuture to manage callbacks in a more intuitive style. Resource contention: Use synchronization primitives (such as locks) to protect shared resources, and consider using thread-safe collections (such as ConcurrentHashMap). Unhandled exceptions: Explicitly handle exceptions in tasks and use an exception handling framework (such as CompletableFuture.exceptionally()) to handle exceptions.

How does the golang framework handle concurrency and asynchronous programming? How does the golang framework handle concurrency and asynchronous programming? Jun 02, 2024 pm 07:49 PM

The Go framework uses Go's concurrency and asynchronous features to provide a mechanism for efficiently handling concurrent and asynchronous tasks: 1. Concurrency is achieved through Goroutine, allowing multiple tasks to be executed at the same time; 2. Asynchronous programming is implemented through channels, which can be executed without blocking the main thread. Task; 3. Suitable for practical scenarios, such as concurrent processing of HTTP requests, asynchronous acquisition of database data, etc.

See all articles