swoole和redis异步任务

本文对比了swoole和redis处理异步任务的效率。在swoole开启4个进程的情况下,其处理异步任务的速度大约是redis的四倍;若swoole仅开启一个进程,则效率与redis相近。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

redis异步任务

interface.php

<?php
for($i=0;$i<100;$i++){
    $msg = "zhezhao[".$i."]";
    $redis = new Redis();
    $redis->connect("127.0.0.1");
    $redis->publish("test",$msg);
    $redis->close();
}

handler.php

<?php
$redis = new Redis();
$redis->connect("127.0.0.1");
$redis->subscribe(array("test"), 'handleFun');
function handleFun($redis, $chan, $data) {
    write($data);
}
function write($data){
    $path = "/tmp/mailList-redis.log";
    $str = "[".date("Y-m-d H:i:s")."]".$data;
    $str .= PHP_EOL;
    file_put_contents($path,$str,FILE_APPEND);
}

swoole异步任务

interface.php

<?php
for($i=0;$i<100;$i++){
    $msg = "zhezhao[".$i."]";
    $client = new swoole_client(SWOOLE_SOCK_TCP);
    $client->connect('127.0.0.1', 9501, 0.5);
    $client->send($msg);
    $client->close();
}

handler.php

<?php
$serv = new swoole_server("127.0.0.1", 9501);
$serv->set(array('task_worker_num' => 4));
$serv->on('receive', function($serv, $fd, $from_id, $data) {
    $task_id = $serv->task($data);
});
$serv->on('task', function ($serv, $task_id, $from_id, $data) {
    handle($data);
    $serv->finish($data);
});
$serv->start();
function handle($data){
    sleep(2);
    mailLog("Send Mail successfully to $data");
}
function mailLog($str){
    $path = "/tmp/mailList.log";
    $str = "[".date("Y-m-d H:i:s")."]".$str;
    $str .= PHP_EOL;
    file_put_contents($path,$str,FILE_APPEND);
}

比较

redis异步任务日志

这里写图片描述

swoole异步任务日志

这里写图片描述

通过对比任务日志我们可以看到,由于swoole开了4个进程执行异步任务,所以处理异步任务的效率大概是redis的四倍,如果swoole只开一个进程的话,效率和redis几乎没有什么差别。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值