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

yipeiwu_com5年前PHP代码库

本文实例讲述了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异步任务日志

这里写图片描述

swoole异步任务日志

这里写图片描述

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

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP进程与线程操作技巧总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php实现在多维数组中查找特定value的方法

本文实例讲述了php实现在多维数组中查找特定value的方法。分享给大家供大家参考。具体如下: 最近做项目,需要从多维数组中查找是否含有特定的key和其对应特定的value,并清除该条数...

深入PHP nl2br()格式化输出的详解

nl2br()函数可将字符串中的换行符转成HTML的换行符号复制代码 代码如下:<?php $str = "最近几天一直在下雨,难过死了 ,球也打不成,鞋子也湿透了。"; echo...

PHP对文件进行加锁、解锁实例

有时候你的php脚本或许需要线程安全的保证,比如进行文件写操作的时候。本文提供了文件加锁函数以及使用示例。文件加锁功能也可以用来获得独享的处理空间,防止脚本执行发生同步错误。 复制代码...

PHP 长文章分页函数 带使用方法,不会分割段落,翻页在底部

复制代码 代码如下: <?php function ff_page($content,$page) { global $expert_id; $PageLength = 2000;...

IIS6.0中配置php服务全过程解析

虽然 LAMP 组合很不错,但是如果想要架设一台同时支持 PHP、ASP、ASP.NET、JSP、Perl 的 Web 虚拟主机服务器,还是用 Windows 2003 的 IIS 6...