How to use PHP microservices to implement distributed task scheduling and dispatch
Overview:
With the rapid development of the Internet, how to efficiently schedule and dispatch tasks has become a This is an important problem faced by many enterprises and developers. Applications that adopt a microservices architecture are better able to handle distributed task scheduling and dispatch. This article will introduce how to use PHP to implement a microservice architecture for distributed task scheduling and dispatch, and provide specific code examples.
Code example for task scheduler:
<?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLibConnectionAMQPStreamConnection; use PhpAmqpLibMessageAMQPMessage; // 连接到RabbitMQ主机 $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); // 定义任务队列 $channel->queue_declare('task_queue', false, true, false, false); // 从命令行参数中获取任务参数 $data = implode(' ', array_slice($argv, 1)); if(empty($data)) { $data = "Hello World!"; } // 创建消息对象 $msg = new AMQPMessage($data, ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]); // 发送消息到任务队列 $channel->basic_publish($msg, '', 'task_queue'); echo " [x] Sent '$data' "; $channel->close(); $connection->close();
Code example for task executor:
<?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLibConnectionAMQPStreamConnection; use PhpAmqpLibMessageAMQPMessage; // 连接到RabbitMQ主机 $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); // 定义任务队列 $channel->queue_declare('task_queue', false, true, false, false); echo " [*] Waiting for messages. To exit press CTRL+C "; // 回调函数,用于处理任务消息 $callback = function ($msg) { echo " [x] Received ", $msg->body, " "; // 模拟任务执行过程 sleep(substr_count($msg->body, '.')); echo " [x] Done "; // 显式确认任务消息已完成 $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); }; // 每次只接受一个任务消息 $channel->basic_qos(null, 1, null); $channel->basic_consume('task_queue', '', false, false, false, false, $callback); while (count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close();
$ php scheduler.php First task
Execute in the terminal window of the task executor:
$ php worker.php
The two applications will communicate with each other and complete the task The process of scheduling and dispatching.
Conclusion:
This article introduces how to use PHP microservices to implement distributed task scheduling and dispatch. By using the RabbitMQ message queue system, we can easily implement asynchronous processing of tasks and separate task scheduling and task execution, improving the scalability and maintainability of the system. Hope this article is helpful to you.
The above is the detailed content of How to use PHP microservices to implement distributed task scheduling and dispatch. For more information, please follow other related articles on the PHP Chinese website!