// 监听数据吸取变乱 public function onReceive(swoole_server $serv, $fd, $from_id, $data) { echo "Get Message From Client {$fd}:{$data}n"; //$this->writeLog('吸取客户端参数:'.$fd .'-'.$data); $res['result'] = 'success'; $serv->send($fd, json_encode($res)); // 同步返回动静给客户端 $serv->task($data); // 执行异步使命 }
/** * @param $serv swoole_server swoole_server工具 * @param $task_id int 使命id * @param $fromid int 投递使命的worker_id * @param $data string 投递的数据 */ public function onTask(swoole_server $serv, $task_id, $from_id, $data) { swoole_timer_tick(30000, function($timer) use ($task_id) { // 启用按时器,每30秒执行一次 $memPercent = $this->getMemoryUsage(); echo date('Y-m-d H:i:s') . '当前内存行使率:'.$memPercent."n"; }); }
/** * @param $serv swoole_server swoole_server工具 * @param $task_id int 使命id * @param $data string 使命返回的数据 */ public function onFinish(swoole_server $serv, $task_id, $data) { // }
// 监听毗连封锁变乱 public function onClose($serv, $fd, $from_id) { echo "Client {$fd} close connectionn"; }
public function stop() { $this->serv->stop(); }
private function getMemoryUsage() { // MEMORY if (false === ($str = @file("/proc/meminfo"))) return false; $str = implode("", $str); preg_match_all("/MemTotals{0,}:+s{0,}([d.]+).+?MemFrees{0,}:+s{0,}([d.]+).+?Cacheds{0,}:+s{0,}([d.]+).+?SwapTotals{0,}:+s{0,}([d.]+).+?SwapFrees{0,}:+s{0,}([d.]+)/s", $str, $buf); //preg_match_all("/Bufferss{0,}:+s{0,}([d.]+)/s", $str, $buffers);
$memTotal = round($buf[1][0]/1024, 2); $memFree = round($buf[2][0]/1024, 2); $memUsed = $memTotal - $memFree; $memPercent = (floatval($memTotal)!=0) ? round($memUsed/$memTotal*100,2):0;
return $memPercent; } }
我们以场景一为例,在onTask启用按时使命,每隔30秒计较一次内存行使率。现实应用中可以把计较好的内存定时刻写入数据库等存储中,然后可以按照前端需求用来渲染成统计图表,如:
接着处事端代码 publictaskServer.php:
<?php require dirname(__DIR__) . '/vendor/autoload.php'; use HellowebaSwooleTask; $opt = [ 'daemonize' => false ]; $ser = new Task($opt); $ser->start();
客户端代码 publictaskClient.php:
<?php class Client { private $client; public function __construct() { $this->client = new swoole_client(SWOOLE_SOCK_TCP); } public function connect() { if( !$this->client->connect("127.0.0.1", 9506 , 1) ) { echo "Error: {$this->client->errMsg}[{$this->client->errCode}]n"; } fwrite(STDOUT, "请输入动静 Please input msg:"); $msg = trim(fgets(STDIN)); $this->client->send( $msg ); $message = $this->client->recv(); echo "Get Message From Server:{$message}n"; } } $client = new Client(); $client->connect();
验证结果
1.启动处事端:
php taskServer.php
2.客户端输入:
[root@localhost public]# php taskClient.php
另开呼吁行窗口,执行
请输入动静 Please input msg:hello
Get Message From Server:{"result":"success"} [root@localhost public]#
3.处事端返回:
假如返回上图中的功效,则按时使命正常运行,我们会发明每隔30秒会输出一条信息。
总结
到此这篇关于php行使Swoole实现毫秒级按时使命的要领的文章就先容到这了,更多相干php Swoole实现毫秒级按时使命内容请搜刮剧本之家早年的文章或继承赏识下面的相干文章但愿各人往后多多支持剧本之家! (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|