最近接手一个对接短信的需求,这个需求本身并没有什么难度,直接按照服务商的要求请求具体的接口就好了。
最开始是使用传统的同步阻塞方式实现了一遍,用户体验并不好,发送短信需要等待,等待服务商的接口返回内容,才继续向下执行。
因为最近在学习Swoole,Swoole 中有一个“异步任务”,就特别适合以下应用场景:需要执行耗时操作,会阻塞主进程
用户不需要等待返回结果
结合官网手册和Latent 的基于 swoole 下 异步消息队列 API,最终简单封装了一个处理API 的类,实现如下:
服务端
服务端是基于本地Tcp,监听9501端口。<?php
class taskServer{
const HOST = "127.0.0.1";
const PORT = 9501;
public $server = null;
public function __construct()
{
$this->server = new SWoole\Server(self::HOST, self::PORT);
$this->server->set(array(
"enable_coroutine" => false, // 关闭协程
"worker_num" => 2, // 开启的进程数 一般为cup核数 1-4 倍
"task_worker_num" => 2, // task进程的数量
'daemonize' => true, // 以守护进程的方式启动
));
// 注册事件
$this->server->on("connect", [$this, "onConnect"]);
$this->server->on("receive", [$this, "onReceive"]);
$this->server->on("close", [$this, "onClose"]);
$this->server->on("task", [$this, "onTask"]);
$this->server->on("finish", [$th