<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                Swoole可以執行異步操作,因此在web頁面將請求提交給Swoole處理后,不用等待返回結果,頁面也不會卡頓。Swoole在后臺將耗時長的操作進行異步處理,從而改善用戶體驗,例如本節要給大家講解的Swoole處理郵件。 ## 準備 請按照上一節:[Swoole實驗室:1-使用Composer構建項目](http://www.hmoore.net/helloweba/swoole/804828),構建好項目。并使用composer安裝郵件發送組件:phpmailer。 ``` composer require phpmailer/phpmailer ``` ## 主程序 在目錄:src/App/下建立Mail.php,用作Swoole服務端主程序。 ``` <?php namespace Helloweba\Swoole; use swoole_server; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; class Mail { protected $serv; protected $host = '127.0.0.1'; protected $port = 9502; // 進程名稱 protected $taskName = 'swooleMailer'; // PID路徑 protected $pidPath = '/run/swooleMail.pid'; // 設置運行時參數 protected $options = [ 'worker_num' => 4, //worker進程數,一般設置為CPU數的1-4倍 'daemonize' => true, //啟用守護進程 'log_file' => '/data/logs/swoole.log', //指定swoole錯誤日志文件 'log_level' => 0, //日志級別 范圍是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR 'dispatch_mode' => 1, //數據包分發策略,1-輪詢模式 'task_worker_num' => 4, //task進程的數量 'task_ipc_mode' => 3, //使用消息隊列通信,并設置為爭搶模式 //'heartbeat_idle_time' => 600, //一個連接如果600秒內未向服務器發送任何數據,此連接將被強制關閉 //'heartbeat_check_interval' => 60, //啟用心跳檢測,每隔60s輪循一次 ]; // 郵件服務器配置 protected $mailConfig = [ 'smtp_server' => 'smtp.163.com', 'username' => 'example@163.com', 'password' => '',// SMTP 密碼/口令 'secure' => 'ssl', //Enable TLS encryption, `ssl` also accepted 'port' => 465, // tcp郵件服務器端口 ]; // 安全密鑰 protected $safeKey = 'MYgGnQE33ytd2jDFADS39DSEWsdD24sK'; public function __construct($mailConfig, $options = []) { // 構建Server對象,監聽端口 $this->serv = new swoole_server($this->host, $this->port); if (!empty($options)) { $this->options = array_merge($this->options, $options); } $this->serv->set($this->options); $this->mailConfig = $mailConfig; // 注冊事件 $this->serv->on('Start', [$this, 'onStart']); $this->serv->on('Connect', [$this, 'onConnect']); $this->serv->on('Receive', [$this, 'onReceive']); $this->serv->on('Task', [$this, 'onTask']); $this->serv->on('Finish', [$this, 'onFinish']); $this->serv->on('Close', [$this, 'onClose']); // 啟動服務 //$this->serv->start(); } protected function init() { // } public function start() { // Run worker $this->serv->start(); } public function onStart($serv) { // 設置進程名 cli_set_process_title($this->taskName); //記錄進程id,腳本實現自動重啟 $pid = "{$serv->master_pid}\n{$serv->manager_pid}"; file_put_contents($this->pidPath, $pid); } //監聽連接進入事件 public function onConnect($serv, $fd, $from_id) { $serv->send($fd, "Hello {$fd}!" ); } // 監聽數據接收事件 public function onReceive(swoole_server $serv, $fd, $from_id, $data) { $res['result'] = 'failed'; $key = $this->safeKey; $req = json_decode($data, true); $action = $req['action']; $token = $req['token']; $timestamp = $req['timestamp']; if (time() - $timestamp > 180) { $res['code'] = '已超時'; $serv->send($fd, json_encode($res)); exit; } $token_get = md5($action.$timestamp.$key); if ($token != $token_get) { $res['msg'] = '非法提交'; $serv->send($fd, json_encode($res)); exit; } $res['result'] = 'success'; $serv->send($fd, json_encode($res)); // 同步返回消息給客戶端 $serv->task($data); // 執行異步任務 } /** * @param $serv swoole_server swoole_server對象 * @param $task_id int 任務id * @param $from_id int 投遞任務的worker_id * @param $data string 投遞的數據 */ public function onTask(swoole_server $serv, $task_id, $from_id, $data) { $res['result'] = 'failed'; $req = json_decode($data, true); $action = $req['action']; echo date('Y-m-d H:i:s')." onTask: [".$action."].\n"; switch ($action) { case 'sendMail': //發送單個郵件 $mailData = [ 'emailAddress' => 'abc@example.com', //接收方,改成自己的郵箱可以測試接收郵件 'subject' => 'swoole實驗室', 'body' => '測試This is the HTML message body <b>in bold!</b>,<br/>歡迎訪問<a href="https://www.helloweba.net/">www.helloweba.net</a>', 'attach' => '/home/swoole/public/a.jpg' ]; $this->sendMail($mailData); break; default: break; } } /** * @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 connection\n"; } public function stop() { $this->serv->stop(); } private function sendMail($mail_data = []) { $mail = new PHPMailer(true); try { $mailConfig = $this->mailConfig; //$mail->SMTPDebug = 2; // 啟用Debug $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = $mailConfig['smtp_server']; // SMTP服務 $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $mailConfig['username']; // SMTP 用戶名 $mail->Password = $mailConfig['password']; // SMTP 密碼/口令 $mail->SMTPSecure = $mailConfig['secure']; // Enable TLS encryption, `ssl` also accepted $mail->Port = $mailConfig['port']; // TCP 端口 $mail->CharSet = "UTF-8"; //字符集 $mail->Encoding = "base64"; //編碼方式 //Recipients $mail->setFrom($mailConfig['username'], 'Helloweba'); //發件人地址,名稱 $mail->addAddress($mail_data['emailAddress'], '親'); // 收件人地址和名稱 //$mail->addCC('hellowebanet@163.com'); // 抄送 //Attachments if (isset($mail_data['attach'])) { $mail->addAttachment($mail_data['attach']); // 添加附件 } //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = $mail_data['subject']; $mail->Body = $mail_data['body']; $mail->send(); return true; } catch (\Exception $e) { echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo; return false; } } } ``` Swoole啟動后,服務端會監聽數據接收事件onReceive(),當接收到客戶端發來的數據時會進行相應的處理。我們在這里對源數據進行驗證,然后作為任務投遞給onTask()。sendMail()是使用phpmailler來發送郵件的,這里可以參考[使用PHPMailer發送帶附件并支持HTML內容的郵件](https://www.helloweba.net/php/205.html)。 ## 運行服務端 在public/目錄下建立mailServer.php,代碼如下: ``` <?php require dirname(__DIR__) . '/vendor/autoload.php'; use Helloweba\Swoole\Mail; $config = [ 'smtp_server' => 'smtp.163.com', //郵件服務器 'username' => 'xxxxx@163.com', //這里是用作發送方的郵箱號 'password' => 'xxxxx',// SMTP 密碼/口令 'secure' => 'ssl', //Enable TLS encryption, `ssl` also accepted 'port' => 465, // tcp郵件服務器端口 ]; $server = new Mail($config); $server->start(); ``` 你可以注冊一個163郵箱,然后開通smtp功能。我DEMO中使用的是163郵箱發郵件發多了被封號了,所以在線演示demo沒上傳了。配置好郵件服務器參數后,運行: ``` php mailServer.php ``` 此時再使用命令`netstat -lntp`查看進程: ![](https://box.kancloud.cn/c1ea04f4dc4caad0872558fd14526ef1_740x159.jpg) 當你看到已經在監聽9502端口時,我們的swoole郵件服務端就已經啟動好了。 ## 運行客戶端 在public/目錄下新建mailClient.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", 9502 , 1) ) { echo "Error: {$this->client->errMsg}[{$this->client->errCode}]\n"; } $action = 'sendMail'; $time = time(); $key = 'MYgGnQE33ytd2jDFADS39DSEWsdD24sK'; $token = md5($action.$time.$key); $data = [ 'action' => $action, 'token' => $token, 'timestamp' => $time ]; $msg = json_encode($data); $this->client->send( $msg ); $message = $this->client->recv(); echo "Get Message From Server:{$message}\n"; } } $client = new Client(); $client->connect(); ``` 運行命令啟動客戶端: ``` php mailClient.php ``` 此時在命令行窗口會返回如下信息: ``` [root@localhost public]# php mailClient.php Get Message From Server:{"result":"success"} ``` 這樣就已經執行郵件發送任務了,如果出現故障,可以查看日志文件/data/logs/swoole.log。 ## 小結 本節是一個簡單的單一郵件發送例子。由Swoole客戶端提交發送郵件的指令到Swoole服務端,服務端接收到需要發送郵件的指令后,調用郵件發送服務來發郵件的。由于發送郵件可能比較耗時,不同的郵件服務器發送耗時也不一樣,經測試單個郵件發送一般在1秒內完成,這個如果在web頁面上發送是可以接受的,但是使用Swoole來發送的話我們提交發送指令就不用管結果了,Swoole在后臺自己進行發送郵件。如果是大批量發送大量郵件時,我們可以使用Swoole+隊列的方案,下節我們來測試批量隊列發送郵件,敬請關注。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看