PHP swoole和redis异步任务实现方法分析
程序员文章站
2022-05-25 23:03:15
本文实例讲述了php swoole和redis异步任务实现方法。分享给大家供大家参考,具体如下:
redis异步任务
interface.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几乎没有什么差别。