Home >Backend Development >PHP Tutorial >Swoole uses task function in PHP-fpm/apache

Swoole uses task function in PHP-fpm/apache

藏色散人
藏色散人forward
2019-08-15 14:26:393049browse

Swoole uses task function in PHP-fpm/apache

● Create a new RedisServer.php

● The code is as follows

<?php
use Swoole\Redis\Server;
$server = new Server("127.0.0.1", 9501, SWOOLE_PROCESS );
$server->set(array(
    &#39;task_worker_num&#39; => 32,
    &#39;worker_num&#39; => 1,
    &#39;task_enable_coroutine&#39; => true,
    &#39;heartbeat_check_interval&#39; => 5,
    &#39;heartbeat_idle_time&#39; => 10,
));
$server->setHandler(&#39;LPUSH&#39;, function ($fd, $data) use ($server) {
    $taskId = $server->task($data);
    if ($taskId === false) {
        $server->send($fd, Server::format(Server::ERROR));
    } else {
        $server->send($fd, Server::format(Server::INT, $taskId));
    }
});
$server->on(&#39;Finish&#39;, function($serv, $taskID, $data) {
    $stats = $serv->stats();
    if ($stats[&#39;tasking_num&#39;] > 10) { //tasking_num 当前正在排队的任务数
        echo "剩余任务信息:" . json_encode($serv->stats()) . "\n";
    }
});
$server->on(&#39;Task&#39;, function ($serv, $data) {
    go(function () {
        usleep(50000);
    });
    var_dump($data);
});
$server->start();

task inside usleep (50000); Simulate task execution time

● Create a new Queue.php

● The code is as follows

<?php
$redis = new Redis;
$redis->connect(&#39;127.0.0.1&#39;, 9501);
$x=1; 
while($x <= 1000) {
  $redis->lpush("myqueue", json_encode(array("hello".$x, "swoole")));
  $x++;
}

Simulate 1000 task delivery

After testing, it will be processed in 1 second

You can follow Task The speed of task execution is adjusted. task_worker_num controls the number of started processes.


● These processes are managed by the swoole bottom layer. The bottom layer will re-create new tasks after a fatal error occurs or the process exits. Process

task_worker_num


● The maximum value shall not exceed SWOOLE_CPU_NUM * 1000

● The processing time of a single task, such as 100ms, which one The process can process 1/0.1=10 tasks in 1 second

● Task delivery speed, for example, 2000 tasks

● 2000/10=200 are generated per second, you need to set task_worker_num => ; 200, enable 200 task processes

Related recommendations: [PHP Tutorial]

The above is the detailed content of Swoole uses task function in PHP-fpm/apache. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete