异步发送邮件

建立执行异步任务的tcp服务器

$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);
    write("收到异步任务:id=$task_id,data=$data");
});

//处理异步任务
$serv->on('task', function ($serv, $task_id, $from_id, $data) {
    handleFun($data);
    //返回任务执行的结果
    $serv->finish();
});

//处理异步任务的结果
$serv->on('finish', function ($serv, $task_id, $data) {
    write("异步任务处理完成:id=$task_id");
});

$serv->start();

function write($str){
        $path = "/tmp/synServer.log";
        $str = "[".date("Y-m-d H:i:s")."]".$str;
        $str .= PHP_EOL;
        file_put_contents($path,$str,FILE_APPEND);
}
function handleFun($data){
        sleep(2);   //休眠2s模拟发邮件时间耗时
        $arr = json_decode($data,true);
        write("mailto ".$arr['mailto']."#subject:".$arr['subject']);
}


建立异步调用tcp服务的客户端


class Client
{
    public function send($msg){
        $client = new swoole_client(SWOOLE_SOCK_TCP);
        //连接到服务器
        if (!$client->connect('127.0.0.1', 9501, 0.5))
        {
            $this->write("connect failed.");
        }
        //向服务器发送数据
        if (!$client->send($msg))
        {
            $this->write("send ".$msg." failed.");
        }
        //关闭连接
        $client->close();
    }
    private function write($str){
        $path = "/tmp/synClient.log";
        $str = "[".date("Y-m-d H:i:s")."]".$str;
        $str .= PHP_EOL;
        file_put_contents($path,$str,FILE_APPEND);
    }
}

在需要执行异步任务时,调用封装的客户端类方法

"synClient.php";
$params = array();
$params['subject'] = "世界你好";
$params['content'] = "四姐你好啊,我是三哥,哈哈哈哈哈哈";
$params['mailto'] = "799631071";
$msg = json_encode($params);
$client = new Client();
$client->send($msg);
echo "[".date("Y-m-d H:i:s")."]继续忙其他的".PHP_EOL;

你可能感兴趣的:(swoole)