服务器之家

服务器之家 > 正文

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

时间:2021-08-12 17:19     来源/作者:koastal

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

redis异步任务

interface.php

?
1
2
3
4
5
6
7
8
<?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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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

?
1
2
3
4
5
6
7
8
<?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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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程序设计有所帮助。

原文链接:https://blog.csdn.net/koastal/article/details/52869140

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部