PHP swoole和redis异步任务实现方法分析

2022-04-14 0 670

本文实例讲述了PHP swoole和redis异步任务实现方法。分享给大家供大家参考,具体如下:

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异步任务日志

PHP swoole和redis异步任务实现方法分析

swoole异步任务日志

PHP swoole和redis异步任务实现方法分析

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

更多关于PHP相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 PHP swoole和redis异步任务实现方法分析 https://www.niceym.com/12221.html