# 系統 linux
# PHP(7.2)+mysql+apache
# 環境軟件(寶塔)
## 準備:
在寶塔平臺上先安裝PHP7.2,安裝好後安裝swoole4.0擴展.[注:在寶塔環境下,執行php -v 顯示的PHP版本默認是當前最高版的,同時swoole也是當前版本的swoole]
## 安裝easyswoole
composer require easyswoole/easyswoole=3.x
php vendor/easyswoole/easyswoole/bin/easyswoole install
這個時候會報錯
Warning: putenv() has been disabled for security reasons in phar:///usr/bin/
說putenv函數被禁止,需要在寶塔接觸禁止函數
## 設置域名綁定easyswoole(apache)
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] fcgi下無效
RewriteRule ^(.*)$ http://127.0.0.1:9501/$1 [QSA,P,L]
#請開啓 proxy_mod proxy_http_mod request_mod
</IfModule>
## 設置配置文件
easyswoole這裏使用開發和生成環境分離的配置,項目根目錄下的dev.php爲開發配置,produce.php爲生產環境
修改easyswoole數據庫配置文件時,ftp無法上傳,報錯說權限不足,因爲是root用戶執行composer下載的easyswoole,所以這裏要修改一下組和所屬用戶爲www
chown -fR www ./*
chgrp -fR www ./*
安裝easyswoole組件 orm(數據庫組件),smtp(郵箱發送),fast-cache(緩存隊列),task(異步),具體請看官方文檔
在 /EasySwooleEvent.php 初始化相關組件,數據庫和隊列
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use EasySwoole\FastCache\Cache;
use EasySwoole\EasySwoole\ServerManager;
public static function initialize()
{
// TODO: Implement initialize() method.
date_default_timezone_set('Asia/Shanghai');
$config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
$config->setMaxObjectNum(20);//配置連接池最大數量
DbManager::getInstance()->addConnection(new Connection($config));
}
public static function mainServerCreate(EventRegister $register)
{
// TODO: Implement mainServerCreate() method.
Cache::getInstance()->setTempDir(EASYSWOOLE_TEMP_DIR)->attachToServer(ServerManager::getInstance()->getSwooleServer());
}
## 設置路由
創建文件 App\HttpController\Router.php
創建這個文件後,程序會自動識別和加載路由
<?php
namespace App\HttpController;
use EasySwoole\Http\AbstractInterface\AbstractRouter;
use FastRoute\RouteCollector;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
class Router extends AbstractRouter
{
function initialize(RouteCollector $routeCollector)
{
$routeCollector->get('/email', '/Index/index');
}
}
當請求 www.test.com/email 時,請求地址是 Index控制器下的index方法
www.test.com的默認路由是 /Index/index## 輸出json
easyswoole 使用 echo,var_dump,exit('xxx) 等方法的結果不會輸出到客戶端(如瀏覽器,ajax,curl),而是輸出在控制檯上
自定義json數據輸出,使用控制器的$this->response()->write方法輸出到客戶端
protected function AjaxJson($code, $data, $msg) {
$json = [
'code' => $code,
'data' => $data,
'msg' => $msg,
];
$this->response()->write(json_encode($json));
return false;
}
注:這裏不能使用die,exit等中止函數## 使用郵箱的SMTP 發送郵箱
### 準備: 需要在 郵箱上開通 IMAP/SMTP權限,並獲取到 授權密碼,獲取到郵箱的 SMTP的服務地址(如smtp.163.com),服務器放行25端口
代碼:
// 目標郵箱
$to_email = '[email protected]';
$this->param = [
'email' => '[email protected]',
'email_password' => 'xxxxx',
];
// 我方郵箱賬號密碼
$email = $this->param['email'];
$email_password = $this->param['email_password'];
$config = new MailerConfig();
$config->setServer('smtp.163.com');
$config->setPort(25);
$config->setSsl(true); // 開啓ssl
$config->setUsername($email);
$config->setPassword($email_password);
$config->setMailFrom($email);
$config->setTimeout(10);//設置客戶端連接超時時間
$config->setMaxPackage(1024*1024*5);//設置包發送的大小:5M
$mimeBean = new Html(); //設置文本或者html格式
$mimeBean->setSubject('郵箱標題');
$mimeBean->setBody('<h1>郵箱內容主體</h1>');
$mailer = new Mailer($config);
$res = $mailer->sendTo($to_email, $mimeBean);
if($res){
$this->AjaxJson(1,$res,'測試發送成功');return false;
}else{
$this->AjaxJson(0,$res,'測試發送失敗');return false;
}
# 隊列和數據庫的簡單使用
// emails 的格式 是 [email protected],[email protected],[email protected],[email protected],[email protected]
$request = $this->request();
$p_emails = explode(',', $request->getRequestParam('emails'));
$job = new Job();
foreach ($p_emails as $ko => $vo) {
// 投遞任務
$job->setData($vo); // 任意類型數據
$job->setQueue("p_emails");
$jobId = Cache::getInstance()->putJob($job);
}
$g_emalis = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
];
// 獲取數據庫數據
$queryBuild = new QueryBuilder();
// 支持參數綁定 第二個參數非必傳
$queryBuild->raw("select * from mail where id=1");
$data = DbManager::getInstance()->query($queryBuild, true, 'default')->getResultOne();
$task = TaskManager::getInstance();
// 數據庫數據存在時
if (isset($data['title'])) {
// 異步執行
$task->async(function () use ($g_emalis, $data) {
foreach ($g_emalis as $ko => $vo) {
// 取出任務
$job = Cache::getInstance()->getJob('p_emails');// Job對象或者null
if ($job === null){
echo "沒有任務\n";
} else {
$chache = $job->toArray();
// var_dump($chache['data']);
echo 'p_email:'.$chache['data'].'----g_email:'.$vo."\n";
echo 'title:'.$data['title'].'----content:'.$data['content']."\n";
// 主動重發隊列 (當隊列全部取出時,會重新重頭開始取出任務)
Cache::getInstance()->releaseJob($job);
}
}
// 清空緩存隊列
Cache::getInstance()->flushJobQueue('p_emails');
});
}