本文實例講述了PHP swoole和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幾乎沒有什么差別。
掃碼二維碼 獲取免費視頻學習資料
- 本文固定鏈接: http://www.wangchenghua.com/post/6736/
- 轉載請注明:轉載必須在正文中標注并保留原文鏈接
- 掃碼: 掃上方二維碼獲取免費視頻資料
查 看2022高級編程視頻教程免費獲取