使用swoole异步发送邮件

父母在时,人生尚有来处。 父母去时,人生只剩归途。
### 安装swoole pecl 安装: `pecl install swoole`

看命令行提示,如果它提示说没有写php.ini,则自己手动在PHP.ini后面加上:
extension = "swoole.so"

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
class Server
{
private $serv;
public function __construct() {
$this->serv = new swoole_server("0.0.0.0", 9501);
$this->serv->set(array(
'worker_num' => 1, //一般设置为服务器CPU数的1-4倍
'daemonize' => 1, //以守护进程执行
'max_request' => 10000,
'dispatch_mode' => 2,
'task_worker_num' => 8, //task进程的数量
"task_ipc_mode " => 3 , //使用消息队列通信,并设置为争抢模式
//"log_file" => "log/taskqueueu.log" ,//日志
));
$this->serv->on('Receive', array($this, 'onReceive'));
// bind callback
$this->serv->on('Task', array($this, 'onTask'));
$this->serv->on('Finish', array($this, 'onFinish'));
$this->serv->start();
}

public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
//echo "Get Message From Client {$fd}:{$data}n";
// send a task to task worker.
$serv->task( $data );
}

public function onTask($serv,$task_id,$from_id, $data) {
$array = json_decode( $data , true );
if ($array['url']) {
return $this->httpGet( $array['url'] , $array['param'] );
}

}

public function onFinish($serv,$task_id, $data) {
//echo "Task {$task_id} finishn";
//echo "Result: {$data}n";
}


protected function httpGet($url,$data){
if ($data) {
$url .='?'.http_build_query($data) ;
}
$curlObj = curl_init(); //初始化curl,
curl_setopt($curlObj, CURLOPT_URL, $url); //设置网址
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); //将curl_exec的结果返回
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curlObj, CURLOPT_HEADER, 0); //是否输出返回头信息
$response = curl_exec($curlObj); //执行
curl_close($curlObj); //关闭会话
return $response;
}

}
$server = new Server();

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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", 9501 , 1) ) {
echo "Connect Error";
}
$data = array(
"url" => "http://192.168.10.19/send_mail" ,
"param" => array(
"username"=>'test',
"password" => 'test'
)
);
$json_data = json_encode($data);
$this->client->send( $json_data );
}
}

$client = new Client();
$client->connect();

查看与关闭

swoole好像没有很便捷的关闭方式。所以只能直接通过关闭进程来关闭。
查看命令:
ps -ef | grep php

结束单个进程:
kill -9 {进程号}

结束所有进程的命令:
killall -9 php