最近参考了几位博主的帖子,模仿写了一个群发邮件功能 参考地址 demo下载
一:基础环境:PHP环境+redis+swoole4
二:实现代码 1:邮件数据写入redis队列 redis.php
$redis = new \Redis();
$redis->connect('127.0.0.1',6379);
$list=[];
for($i=0;$i<10;$i++)
{
$list[$i]['address']='xxxxx@qq.com';
$list[$i]['subject']='群发邮件,序列'.$i;
$list[$i]['body']='发送时间:'.date('Y-m-d H:i:s',time());
$data=json_encode($list[$i]);
$redis->rpush('mailList',$data);
}
2:服务端代码 server.php
$object = new MailServer();
$setting = [
'log_file' => 'swoole.log',
'worker_num' => 4,
'task_worker_num' => 10,
];
$server = new swoole_server("127.0.0.1", 9501);
$server->set($setting);
$server->on('WorkerStart', array($object, 'onWorkerStart'));
$server->on('Connect', array($object, 'onConnect'));
$server->on('Receive', array($object, 'onReceive'));
$server->on('Close', array($object, 'onClose'));
$server->on('Task', array($object, 'onTask'));
$server->on('Finish', array($object, 'onFinish'));
$server->start();
class MailServer
{
private $handle;
public function __construct()
{
require 'Mail.php';
}
public function onWorkerStart($server, $workerId)
{
$mailConfig = require 'MailConfig.php';
$this->handle = new Mail($mailConfig);
}
public function onConnect($server, $fd, $reactorId)
{
}
public function onReceive($server, $fd, $reactorId, $data)
{
$server->task($data);
$return['code'] = 01;
$return['msg'] = '投递一个邮件任务';
$server->send($fd, json_encode($return));
}
public function onTask($server, $taskId, $workerId, $data)
{
switch ($data)
{
case 1:
$mailData=[
'addtess'=>'xxx@163.com',
'subject'=>'单条邮件',
'body'=>'发送时间:'.date('Y-m-d H:i:s',time()),
];
$this->sendMail();
break;
case 2:
$this->sendListMail();
break;
default:
break;
}
}
public function onFinish($server, $task_id, $data)
{
}
public function onClose($server, $fd, $reactorId)
{
}
protected function sendMail($data)
{
$data = json_decode($data, true);
$this->handle->send($data['address'], $data['subject'], $data['body']);
}
protected function sendListMail()
{
$redis=new \Redis();
$redis->connect('127.0.0.1',6379);
swoole_timer_tick(60000, function($timer) use ($redis) {
$value = $redis->lpop('mailList');
if($value)
{
$json = json_decode($value, true);
$start = microtime(true);
$data = json_decode($value, true);
$rs = $this->handle->send($data['address'], $data['subject'], $data['body']);
$end = microtime(true);
if ($rs)
{
echo '发送成功! 邮件标题:'.$data['subject'].', 耗时:'. round($end - $start, 3).'秒'.PHP_EOL;
}
else
{
$redis->rpush("mailError", $value);
}
}
else
{
swoole_timer_clear($timer);
echo "Emaillist出队完成";
}
});
}
3:客户端代码 client.php
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1))
{
exit("connect failed. Error: {$client->errCode}\n");
}
$type=2;
$client->send(json_encode($type));
echo $client->recv();
$client->close();
4:执行任务 1.开启服务
php server.php
- 写入redis队列
php redis.php
- 客户端执行
php client.php
效果如下:
至此,简单群发功能完成;
|