初始化项目
This commit is contained in:
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
ThinkPHP 6.0 Workerman 扩展
|
||||
===============
|
||||
|
||||
## 安装
|
||||
|
||||
```
|
||||
composer require topthink/think-worker
|
||||
```
|
||||
|
||||
## 使用方法
|
||||
|
||||
### HttpServer
|
||||
|
||||
在命令行启动服务端
|
||||
~~~
|
||||
php think worker
|
||||
~~~
|
||||
|
||||
然后就可以通过浏览器直接访问当前应用
|
||||
|
||||
~~~
|
||||
http://localhost:2346
|
||||
~~~
|
||||
|
||||
linux下面可以支持下面指令
|
||||
~~~
|
||||
php think worker [start|stop|reload|restart|status]
|
||||
~~~
|
||||
|
||||
workerman的参数可以在应用配置目录下的worker.php里面配置。
|
||||
|
||||
由于onWorkerStart运行的时候没有HTTP_HOST,因此最好在应用配置文件中设置app_host
|
||||
|
||||
### SocketServer
|
||||
|
||||
在命令行启动服务端
|
||||
~~~
|
||||
php think worker:server
|
||||
~~~
|
||||
|
||||
默认会在0.0.0.0:2345开启一个websocket服务。
|
||||
|
||||
如果需要自定义参数,可以在config/worker_server.php中进行配置,包括:
|
||||
|
||||
配置参数 | 描述
|
||||
--- | ---
|
||||
protocol| 协议
|
||||
host | 监听地址
|
||||
port | 监听端口
|
||||
socket | 完整的socket地址
|
||||
|
||||
并且支持workerman所有的参数。
|
||||
也支持使用闭包方式定义相关事件回调。
|
||||
|
||||
~~~
|
||||
return [
|
||||
'socket' => 'http://127.0.0.1:8000',
|
||||
'name' => 'thinkphp',
|
||||
'count' => 4,
|
||||
'onMessage' => function($connection, $data) {
|
||||
$connection->send(json_encode($data));
|
||||
},
|
||||
];
|
||||
~~~
|
||||
|
||||
也支持使用自定义类作为Worker服务入口文件类。例如,我们可以创建一个服务类(必须要继承 think\worker\Server),然后设置属性和添加回调方法
|
||||
|
||||
~~~
|
||||
<?php
|
||||
namespace app\http;
|
||||
|
||||
use think\worker\Server;
|
||||
|
||||
class Worker extends Server
|
||||
{
|
||||
protected $socket = 'http://0.0.0.0:2346';
|
||||
|
||||
public function onMessage($connection,$data)
|
||||
{
|
||||
$connection->send(json_encode($data));
|
||||
}
|
||||
}
|
||||
~~~
|
||||
支持workerman所有的回调方法定义(回调方法必须是public类型)
|
||||
|
||||
然后在worker_server.php中增加配置参数:
|
||||
~~~
|
||||
return [
|
||||
'worker_class' => 'app\http\Worker',
|
||||
];
|
||||
~~~
|
||||
|
||||
定义该参数后,其它配置参数均不再有效。
|
||||
|
||||
在命令行启动服务端
|
||||
~~~
|
||||
php think worker:server
|
||||
~~~
|
||||
|
||||
然后在浏览器里面访问
|
||||
~~~
|
||||
http://localhost:2346
|
||||
~~~
|
||||
|
||||
如果在Linux下面,同样支持reload|restart|stop|status 操作
|
||||
~~~
|
||||
php think worker:server reload
|
||||
~~~
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "topthink/think-worker",
|
||||
"description": "workerman extend for thinkphp6.0",
|
||||
"license": "Apache-2.0",
|
||||
"authors": [
|
||||
{
|
||||
"name": "liu21st",
|
||||
"email": "liu21st@gmail.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"workerman/workerman": "^3.5.23",
|
||||
"workerman/gateway-worker": "^3.0.0",
|
||||
"topthink/framework": "^6.0",
|
||||
"ext-fileinfo": "*"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"think\\worker\\": "src"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"think":{
|
||||
"services":[
|
||||
"think\\worker\\Service"
|
||||
],
|
||||
"config":{
|
||||
"worker": "src/config/worker.php",
|
||||
"worker_server": "src/config/server.php",
|
||||
"gateway_worker": "src/config/gateway.php"
|
||||
}
|
||||
}
|
||||
},
|
||||
"minimum-stability": "dev"
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\worker;
|
||||
|
||||
use think\App;
|
||||
use think\exception\Handle;
|
||||
use think\exception\HttpException;
|
||||
use Workerman\Protocols\Http as WorkerHttp;
|
||||
|
||||
/**
|
||||
* Worker应用对象
|
||||
*/
|
||||
class Application extends App
|
||||
{
|
||||
/**
|
||||
* 处理Worker请求
|
||||
* @access public
|
||||
* @param \Workerman\Connection\TcpConnection $connection
|
||||
* @param void
|
||||
*/
|
||||
public function worker($connection)
|
||||
{
|
||||
try {
|
||||
$this->beginTime = microtime(true);
|
||||
$this->beginMem = memory_get_usage();
|
||||
$this->db->clearQueryTimes();
|
||||
|
||||
$pathinfo = ltrim(strpos($_SERVER['REQUEST_URI'], '?') ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'], '/');
|
||||
|
||||
$this->request
|
||||
->setPathinfo($pathinfo)
|
||||
->withInput($GLOBALS['HTTP_RAW_POST_DATA']);
|
||||
|
||||
while (ob_get_level() > 1) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
ob_start();
|
||||
$response = $this->http->run();
|
||||
$content = ob_get_clean();
|
||||
|
||||
ob_start();
|
||||
|
||||
$response->send();
|
||||
$this->http->end($response);
|
||||
|
||||
$content .= ob_get_clean() ?: '';
|
||||
|
||||
$this->httpResponseCode($response->getCode());
|
||||
|
||||
foreach ($response->getHeader() as $name => $val) {
|
||||
// 发送头部信息
|
||||
WorkerHttp::header($name . (!is_null($val) ? ':' . $val : ''));
|
||||
}
|
||||
|
||||
if (strtolower($_SERVER['HTTP_CONNECTION']) === "keep-alive") {
|
||||
$connection->send($content);
|
||||
} else {
|
||||
$connection->close($content);
|
||||
}
|
||||
} catch (HttpException | \Exception | \Throwable $e) {
|
||||
$this->exception($connection, $e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否运行在命令行下
|
||||
* @return bool
|
||||
*/
|
||||
public function runningInConsole(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function httpResponseCode($code = 200)
|
||||
{
|
||||
WorkerHttp::responseCode($code);
|
||||
}
|
||||
|
||||
protected function exception($connection, $e)
|
||||
{
|
||||
if ($e instanceof \Exception) {
|
||||
$handler = $this->make(Handle::class);
|
||||
$handler->report($e);
|
||||
|
||||
$resp = $handler->render($this->request, $e);
|
||||
$content = $resp->getContent();
|
||||
$code = $resp->getCode();
|
||||
|
||||
$this->httpResponseCode($code);
|
||||
$connection->send($content);
|
||||
} else {
|
||||
$this->httpResponseCode(500);
|
||||
$connection->send($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
namespace think\worker;
|
||||
|
||||
use think\Cookie as BaseCookie;
|
||||
use Workerman\Protocols\Http as WorkerHttp;
|
||||
|
||||
/**
|
||||
* Workerman Cookie类
|
||||
*/
|
||||
class Cookie extends BaseCookie
|
||||
{
|
||||
/**
|
||||
* 保存Cookie
|
||||
* @access public
|
||||
* @param string $name cookie名称
|
||||
* @param string $value cookie值
|
||||
* @param int $expire cookie过期时间
|
||||
* @param string $path 有效的服务器路径
|
||||
* @param string $domain 有效域名/子域名
|
||||
* @param bool $secure 是否仅仅通过HTTPS
|
||||
* @param bool $httponly 仅可通过HTTP访问
|
||||
* @param string $samesite 防止CSRF攻击和用户追踪
|
||||
* @return void
|
||||
*/
|
||||
protected function saveCookie(string $name, string $value, int $expire, string $path, string $domain, bool $secure, bool $httponly, string $samesite): void
|
||||
{
|
||||
WorkerHttp::setCookie($name, $value, $expire, $path, $domain, $secure, $httponly);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
namespace think\worker;
|
||||
|
||||
use GatewayWorker\Lib\Gateway;
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* Worker 命令行服务类
|
||||
*/
|
||||
class Events
|
||||
{
|
||||
/**
|
||||
* onWorkerStart 事件回调
|
||||
* 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
|
||||
*
|
||||
* @access public
|
||||
* @param \Workerman\Worker $businessWorker
|
||||
* @return void
|
||||
*/
|
||||
public static function onWorkerStart(Worker $businessWorker)
|
||||
{
|
||||
$app = new Application;
|
||||
$app->initialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* onConnect 事件回调
|
||||
* 当客户端连接上gateway进程时(TCP三次握手完毕时)触发
|
||||
*
|
||||
* @access public
|
||||
* @param int $client_id
|
||||
* @return void
|
||||
*/
|
||||
public static function onConnect($client_id)
|
||||
{
|
||||
Gateway::sendToCurrentClient("Your client_id is $client_id");
|
||||
}
|
||||
|
||||
/**
|
||||
* onWebSocketConnect 事件回调
|
||||
* 当客户端连接上gateway完成websocket握手时触发
|
||||
*
|
||||
* @param integer $client_id 断开连接的客户端client_id
|
||||
* @param mixed $data
|
||||
* @return void
|
||||
*/
|
||||
public static function onWebSocketConnect($client_id, $data)
|
||||
{
|
||||
var_export($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* onMessage 事件回调
|
||||
* 当客户端发来数据(Gateway进程收到数据)后触发
|
||||
*
|
||||
* @access public
|
||||
* @param int $client_id
|
||||
* @param mixed $data
|
||||
* @return void
|
||||
*/
|
||||
public static function onMessage($client_id, $data)
|
||||
{
|
||||
Gateway::sendToAll($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* onClose 事件回调 当用户断开连接时触发的方法
|
||||
*
|
||||
* @param integer $client_id 断开连接的客户端client_id
|
||||
* @return void
|
||||
*/
|
||||
public static function onClose($client_id)
|
||||
{
|
||||
GateWay::sendToAll("client[$client_id] logout\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* onWorkerStop 事件回调
|
||||
* 当businessWorker进程退出时触发。每个进程生命周期内都只会触发一次。
|
||||
*
|
||||
* @param \Workerman\Worker $businessWorker
|
||||
* @return void
|
||||
*/
|
||||
public static function onWorkerStop(Worker $businessWorker)
|
||||
{
|
||||
echo "WorkerStop\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
namespace think\worker;
|
||||
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use Workerman\Connection\TcpConnection;
|
||||
use Workerman\Lib\Timer;
|
||||
use Workerman\Protocols\Http as WorkerHttp;
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* Worker http server 命令行服务类
|
||||
*/
|
||||
class Http extends Server
|
||||
{
|
||||
protected $app;
|
||||
protected $rootPath;
|
||||
protected $root;
|
||||
protected $appInit;
|
||||
protected $monitor;
|
||||
protected $lastMtime;
|
||||
/** @var array Mime mapping. */
|
||||
protected static $mimeTypeMap = [];
|
||||
|
||||
/**
|
||||
* 架构函数
|
||||
* @access public
|
||||
* @param string $host 监听地址
|
||||
* @param int $port 监听端口
|
||||
* @param array $context 参数
|
||||
*/
|
||||
public function __construct($host, $port, $context = [])
|
||||
{
|
||||
$this->worker = new Worker('http://' . $host . ':' . $port, $context);
|
||||
|
||||
// 设置回调
|
||||
foreach ($this->event as $event) {
|
||||
if (method_exists($this, $event)) {
|
||||
$this->worker->$event = [$this, $event];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function setRootPath($path)
|
||||
{
|
||||
$this->rootPath = $path;
|
||||
}
|
||||
|
||||
public function appInit(\Closure $closure)
|
||||
{
|
||||
$this->appInit = $closure;
|
||||
}
|
||||
|
||||
public function setRoot($path)
|
||||
{
|
||||
$this->root = $path;
|
||||
}
|
||||
|
||||
public function setStaticOption($name, $value)
|
||||
{
|
||||
Worker::${$name} = $value;
|
||||
}
|
||||
|
||||
public function setMonitor($interval = 2, $path = [])
|
||||
{
|
||||
$this->monitor['interval'] = $interval;
|
||||
$this->monitor['path'] = (array) $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置参数
|
||||
* @access public
|
||||
* @param array $option 参数
|
||||
* @return void
|
||||
*/
|
||||
public function option(array $option)
|
||||
{
|
||||
// 设置参数
|
||||
if (!empty($option)) {
|
||||
foreach ($option as $key => $val) {
|
||||
$this->worker->$key = $val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* onWorkerStart 事件回调
|
||||
* @access public
|
||||
* @param \Workerman\Worker $worker
|
||||
* @return void
|
||||
*/
|
||||
public function onWorkerStart($worker)
|
||||
{
|
||||
$this->initMimeTypeMap();
|
||||
$this->app = new Application($this->rootPath);
|
||||
|
||||
if ($this->appInit) {
|
||||
call_user_func_array($this->appInit, [$this->app]);
|
||||
}
|
||||
|
||||
$this->app->initialize();
|
||||
|
||||
$this->lastMtime = time();
|
||||
|
||||
$this->app->workerman = $worker;
|
||||
|
||||
$this->app->bind([
|
||||
'think\Cookie' => Cookie::class,
|
||||
]);
|
||||
|
||||
if (0 == $worker->id && $this->monitor) {
|
||||
$paths = $this->monitor['path'];
|
||||
$timer = $this->monitor['interval'] ?: 2;
|
||||
|
||||
Timer::add($timer, function () use ($paths) {
|
||||
foreach ($paths as $path) {
|
||||
$dir = new RecursiveDirectoryIterator($path);
|
||||
$iterator = new RecursiveIteratorIterator($dir);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if (pathinfo($file, PATHINFO_EXTENSION) != 'php') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->lastMtime < $file->getMTime()) {
|
||||
echo '[update]' . $file . "\n";
|
||||
posix_kill(posix_getppid(), SIGUSR1);
|
||||
$this->lastMtime = $file->getMTime();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* onMessage 事件回调
|
||||
* @access public
|
||||
* @param TcpConnection $connection
|
||||
* @param mixed $data
|
||||
* @return void
|
||||
*/
|
||||
public function onMessage($connection, $data)
|
||||
{
|
||||
$uri = parse_url($_SERVER['REQUEST_URI']);
|
||||
$path = $uri['path'] ?? '/';
|
||||
|
||||
$file = $this->root . $path;
|
||||
|
||||
if (!is_file($file)) {
|
||||
$this->app->worker($connection, $data);
|
||||
} else {
|
||||
$this->sendFile($connection, $file);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 访问资源文件
|
||||
* @access protected
|
||||
* @param TcpConnection $connection
|
||||
* @param string $file 文件名
|
||||
* @return string
|
||||
*/
|
||||
protected function sendFile($connection, $file)
|
||||
{
|
||||
$info = stat($file);
|
||||
$modifiyTime = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' ' . date_default_timezone_get() : '';
|
||||
|
||||
if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info) {
|
||||
// Http 304.
|
||||
if ($modifiyTime === $_SERVER['HTTP_IF_MODIFIED_SINCE']) {
|
||||
// 304
|
||||
WorkerHttp::header('HTTP/1.1 304 Not Modified');
|
||||
// Send nothing but http headers..
|
||||
return $connection->close('');
|
||||
}
|
||||
}
|
||||
|
||||
$mimeType = $this->getMimeType($file);
|
||||
|
||||
WorkerHttp::header('HTTP/1.1 200 OK');
|
||||
WorkerHttp::header('Connection: keep-alive');
|
||||
|
||||
if ($mimeType) {
|
||||
WorkerHttp::header('Content-Type: ' . $mimeType);
|
||||
} else {
|
||||
WorkerHttp::header('Content-Type: application/octet-stream');
|
||||
$fileinfo = pathinfo($file);
|
||||
$filename = $fileinfo['filename'] ?? '';
|
||||
WorkerHttp::header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
}
|
||||
|
||||
if ($modifiyTime) {
|
||||
WorkerHttp::header('Last-Modified: ' . $modifiyTime);
|
||||
}
|
||||
|
||||
WorkerHttp::header('Content-Length: ' . filesize($file));
|
||||
|
||||
ob_start();
|
||||
readfile($file);
|
||||
$content = ob_get_clean();
|
||||
|
||||
return $connection->send($content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件类型信息
|
||||
* @access protected
|
||||
* @param string $filename 文件名
|
||||
* @return string
|
||||
*/
|
||||
protected function getMimeType(string $filename)
|
||||
{
|
||||
$file_info = pathinfo($filename);
|
||||
$extension = $file_info['extension'] ?? '';
|
||||
|
||||
if (isset(self::$mimeTypeMap[$extension])) {
|
||||
$mime = self::$mimeTypeMap[$extension];
|
||||
} else {
|
||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$mime = finfo_file($finfo, $filename);
|
||||
}
|
||||
|
||||
return $mime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Init mime map.
|
||||
*
|
||||
* @return void
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected function initMimeTypeMap()
|
||||
{
|
||||
$mime_file = WorkerHttp::getMimeTypesFile();
|
||||
|
||||
if (!is_file($mime_file)) {
|
||||
Worker::log("$mime_file mime.type file not fond");
|
||||
return;
|
||||
}
|
||||
|
||||
$items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
|
||||
if (!is_array($items)) {
|
||||
Worker::log("get $mime_file mime.type content fail");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($items as $content) {
|
||||
if (preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
|
||||
$mime_type = $match[1];
|
||||
$workerman_file_extension_var = $match[2];
|
||||
$workerman_file_extension_array = explode(' ', substr($workerman_file_extension_var, 0, -1));
|
||||
foreach ($workerman_file_extension_array as $workerman_file_extension) {
|
||||
self::$mimeTypeMap[$workerman_file_extension] = $mime_type;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function start()
|
||||
{
|
||||
Worker::runAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function stop()
|
||||
{
|
||||
Worker::stopAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\worker;
|
||||
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* Worker控制器扩展类
|
||||
*/
|
||||
abstract class Server
|
||||
{
|
||||
protected $worker;
|
||||
protected $socket = '';
|
||||
protected $protocol = 'http';
|
||||
protected $host = '0.0.0.0';
|
||||
protected $port = '2346';
|
||||
protected $option = [];
|
||||
protected $context = [];
|
||||
protected $event = ['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerReload', 'onWebSocketConnect'];
|
||||
|
||||
/**
|
||||
* 架构函数
|
||||
* @access public
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
// 实例化 Websocket 服务
|
||||
$this->worker = new Worker($this->socket ?: $this->protocol . '://' . $this->host . ':' . $this->port, $this->context);
|
||||
|
||||
// 设置参数
|
||||
if (!empty($this->option)) {
|
||||
foreach ($this->option as $key => $val) {
|
||||
$this->worker->$key = $val;
|
||||
}
|
||||
}
|
||||
|
||||
// 设置回调
|
||||
foreach ($this->event as $event) {
|
||||
if (method_exists($this, $event)) {
|
||||
$this->worker->$event = [$this, $event];
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化
|
||||
$this->init();
|
||||
}
|
||||
|
||||
protected function init()
|
||||
{
|
||||
}
|
||||
|
||||
public function start()
|
||||
{
|
||||
Worker::runAll();
|
||||
}
|
||||
|
||||
public function __set($name, $value)
|
||||
{
|
||||
$this->worker->$name = $value;
|
||||
}
|
||||
|
||||
public function __call($method, $args)
|
||||
{
|
||||
call_user_func_array([$this->worker, $method], $args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
namespace think\worker;
|
||||
|
||||
use think\Service as BaseService;
|
||||
|
||||
class Service extends BaseService
|
||||
{
|
||||
public function register()
|
||||
{
|
||||
$this->commands([
|
||||
'worker' => '\\think\\worker\\command\\Worker',
|
||||
'worker:server' => '\\think\\worker\\command\\Server',
|
||||
'worker:gateway' => '\\think\\worker\\command\\GatewayWorker',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\worker\command;
|
||||
|
||||
use GatewayWorker\BusinessWorker;
|
||||
use GatewayWorker\Gateway;
|
||||
use GatewayWorker\Register;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\input\Argument;
|
||||
use think\console\input\Option;
|
||||
use think\console\Output;
|
||||
use think\facade\Config;
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* Worker 命令行类
|
||||
*/
|
||||
class GatewayWorker extends Command
|
||||
{
|
||||
public function configure()
|
||||
{
|
||||
$this->setName('worker:gateway')
|
||||
->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
|
||||
->addOption('host', 'H', Option::VALUE_OPTIONAL, 'the host of workerman server.', null)
|
||||
->addOption('port', 'p', Option::VALUE_OPTIONAL, 'the port of workerman server.', null)
|
||||
->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.')
|
||||
->setDescription('GatewayWorker Server for ThinkPHP');
|
||||
}
|
||||
|
||||
public function execute(Input $input, Output $output)
|
||||
{
|
||||
$action = $input->getArgument('action');
|
||||
|
||||
if (DIRECTORY_SEPARATOR !== '\\') {
|
||||
if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status', 'connections'])) {
|
||||
$output->writeln("Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
global $argv;
|
||||
array_shift($argv);
|
||||
array_shift($argv);
|
||||
array_unshift($argv, 'think', $action);
|
||||
} else {
|
||||
$output->writeln("GatewayWorker Not Support On Windows.");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if ('start' == $action) {
|
||||
$output->writeln('Starting GatewayWorker server...');
|
||||
}
|
||||
|
||||
$option = Config::get('gateway_worker');
|
||||
|
||||
if ($input->hasOption('host')) {
|
||||
$host = $input->getOption('host');
|
||||
} else {
|
||||
$host = !empty($option['host']) ? $option['host'] : '0.0.0.0';
|
||||
}
|
||||
|
||||
if ($input->hasOption('port')) {
|
||||
$port = $input->getOption('port');
|
||||
} else {
|
||||
$port = !empty($option['port']) ? $option['port'] : '2347';
|
||||
}
|
||||
|
||||
$this->start($host, (int) $port, $option);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动
|
||||
* @access public
|
||||
* @param string $host 监听地址
|
||||
* @param integer $port 监听端口
|
||||
* @param array $option 参数
|
||||
* @return void
|
||||
*/
|
||||
public function start(string $host, int $port, array $option = [])
|
||||
{
|
||||
$registerAddress = !empty($option['registerAddress']) ? $option['registerAddress'] : '127.0.0.1:1236';
|
||||
|
||||
if (!empty($option['register_deploy'])) {
|
||||
// 分布式部署的时候其它服务器可以关闭register服务
|
||||
// 注意需要设置不同的lanIp
|
||||
$this->register($registerAddress);
|
||||
}
|
||||
|
||||
// 启动businessWorker
|
||||
if (!empty($option['businessWorker_deploy'])) {
|
||||
$this->businessWorker($registerAddress, $option['businessWorker'] ?? []);
|
||||
}
|
||||
|
||||
// 启动gateway
|
||||
if (!empty($option['gateway_deploy'])) {
|
||||
$this->gateway($registerAddress, $host, $port, $option);
|
||||
}
|
||||
|
||||
Worker::runAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动register
|
||||
* @access public
|
||||
* @param string $registerAddress
|
||||
* @return void
|
||||
*/
|
||||
public function register(string $registerAddress)
|
||||
{
|
||||
// 初始化register
|
||||
new Register('text://' . $registerAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动businessWorker
|
||||
* @access public
|
||||
* @param string $registerAddress registerAddress
|
||||
* @param array $option 参数
|
||||
* @return void
|
||||
*/
|
||||
public function businessWorker(string $registerAddress, array $option = [])
|
||||
{
|
||||
// 初始化 bussinessWorker 进程
|
||||
$worker = new BusinessWorker();
|
||||
|
||||
$this->option($worker, $option);
|
||||
|
||||
$worker->registerAddress = $registerAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动gateway
|
||||
* @access public
|
||||
* @param string $registerAddress registerAddress
|
||||
* @param string $host 服务地址
|
||||
* @param integer $port 监听端口
|
||||
* @param array $option 参数
|
||||
* @return void
|
||||
*/
|
||||
public function gateway(string $registerAddress, string $host, int $port, array $option = [])
|
||||
{
|
||||
// 初始化 gateway 进程
|
||||
if (!empty($option['socket'])) {
|
||||
$socket = $option['socket'];
|
||||
unset($option['socket']);
|
||||
} else {
|
||||
$protocol = !empty($option['protocol']) ? $option['protocol'] : 'websocket';
|
||||
$socket = $protocol . '://' . $host . ':' . $port;
|
||||
unset($option['host'], $option['port'], $option['protocol']);
|
||||
}
|
||||
|
||||
$gateway = new Gateway($socket, $option['context'] ?? []);
|
||||
|
||||
// 以下设置参数都可以在配置文件中重新定义覆盖
|
||||
$gateway->name = 'Gateway';
|
||||
$gateway->count = 4;
|
||||
$gateway->lanIp = '127.0.0.1';
|
||||
$gateway->startPort = 2000;
|
||||
$gateway->pingInterval = 30;
|
||||
$gateway->pingNotResponseLimit = 0;
|
||||
$gateway->pingData = '{"type":"ping"}';
|
||||
$gateway->registerAddress = $registerAddress;
|
||||
|
||||
// 全局静态属性设置
|
||||
foreach ($option as $name => $val) {
|
||||
if (in_array($name, ['stdoutFile', 'daemonize', 'pidFile', 'logFile'])) {
|
||||
Worker::${$name} = $val;
|
||||
unset($option[$name]);
|
||||
}
|
||||
}
|
||||
|
||||
$this->option($gateway, $option);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置参数
|
||||
* @access protected
|
||||
* @param Worker $worker Worker对象
|
||||
* @param array $option 参数
|
||||
* @return void
|
||||
*/
|
||||
protected function option(Worker $worker, array $option = [])
|
||||
{
|
||||
// 设置参数
|
||||
if (!empty($option)) {
|
||||
foreach ($option as $key => $val) {
|
||||
$worker->$key = $val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\worker\command;
|
||||
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\input\Argument;
|
||||
use think\console\input\Option;
|
||||
use think\console\Output;
|
||||
use think\facade\App;
|
||||
use think\facade\Config;
|
||||
use think\worker\Server as WorkerServer;
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* Worker Server 命令行类
|
||||
*/
|
||||
class Server extends Command
|
||||
{
|
||||
protected $config = [];
|
||||
|
||||
public function configure()
|
||||
{
|
||||
$this->setName('worker:server')
|
||||
->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
|
||||
->addOption('host', 'H', Option::VALUE_OPTIONAL, 'the host of workerman server.', null)
|
||||
->addOption('port', 'p', Option::VALUE_OPTIONAL, 'the port of workerman server.', null)
|
||||
->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.')
|
||||
->setDescription('Workerman Server for ThinkPHP');
|
||||
}
|
||||
|
||||
public function execute(Input $input, Output $output)
|
||||
{
|
||||
$action = $input->getArgument('action');
|
||||
|
||||
if (DIRECTORY_SEPARATOR !== '\\') {
|
||||
if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status', 'connections'])) {
|
||||
$output->writeln("<error>Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .</error>");
|
||||
return false;
|
||||
}
|
||||
|
||||
global $argv;
|
||||
array_shift($argv);
|
||||
array_shift($argv);
|
||||
array_unshift($argv, 'think', $action);
|
||||
} elseif ('start' != $action) {
|
||||
$output->writeln("<error>Not Support action:{$action} on Windows.</error>");
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->config = Config::get('worker_server');
|
||||
|
||||
if ('start' == $action) {
|
||||
$output->writeln('Starting Workerman server...');
|
||||
}
|
||||
|
||||
// 自定义服务器入口类
|
||||
if (!empty($this->config['worker_class'])) {
|
||||
$class = (array) $this->config['worker_class'];
|
||||
|
||||
foreach ($class as $server) {
|
||||
$this->startServer($server);
|
||||
}
|
||||
|
||||
// Run worker
|
||||
Worker::runAll();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!empty($this->config['socket'])) {
|
||||
$socket = $this->config['socket'];
|
||||
list($host, $port) = explode(':', $socket);
|
||||
} else {
|
||||
$host = $this->getHost();
|
||||
$port = $this->getPort();
|
||||
$protocol = !empty($this->config['protocol']) ? $this->config['protocol'] : 'websocket';
|
||||
$socket = $protocol . '://' . $host . ':' . $port;
|
||||
unset($this->config['host'], $this->config['port'], $this->config['protocol']);
|
||||
}
|
||||
|
||||
if (isset($this->config['context'])) {
|
||||
$context = $this->config['context'];
|
||||
unset($this->config['context']);
|
||||
} else {
|
||||
$context = [];
|
||||
}
|
||||
|
||||
$worker = new Worker($socket, $context);
|
||||
|
||||
if (empty($this->config['pidFile'])) {
|
||||
$this->config['pidFile'] = App::getRootPath() . 'runtime/worker.pid';
|
||||
}
|
||||
|
||||
// 避免pid混乱
|
||||
$this->config['pidFile'] .= '_' . $port;
|
||||
|
||||
// 开启守护进程模式
|
||||
if ($this->input->hasOption('daemon')) {
|
||||
Worker::$daemonize = true;
|
||||
}
|
||||
|
||||
if (!empty($this->config['ssl'])) {
|
||||
$this->config['transport'] = 'ssl';
|
||||
unset($this->config['ssl']);
|
||||
}
|
||||
|
||||
// 设置服务器参数
|
||||
foreach ($this->config as $name => $val) {
|
||||
if (in_array($name, ['stdoutFile', 'daemonize', 'pidFile', 'logFile'])) {
|
||||
Worker::${$name} = $val;
|
||||
} else {
|
||||
$worker->$name = $val;
|
||||
}
|
||||
}
|
||||
|
||||
// Run worker
|
||||
Worker::runAll();
|
||||
}
|
||||
|
||||
protected function startServer(string $class)
|
||||
{
|
||||
if (class_exists($class)) {
|
||||
$worker = new $class;
|
||||
if (!$worker instanceof WorkerServer) {
|
||||
$this->output->writeln("<error>Worker Server Class Must extends \\think\\worker\\Server</error>");
|
||||
}
|
||||
} else {
|
||||
$this->output->writeln("<error>Worker Server Class Not Exists : {$class}</error>");
|
||||
}
|
||||
}
|
||||
|
||||
protected function getHost()
|
||||
{
|
||||
if ($this->input->hasOption('host')) {
|
||||
$host = $this->input->getOption('host');
|
||||
} else {
|
||||
$host = !empty($this->config['host']) ? $this->config['host'] : '0.0.0.0';
|
||||
}
|
||||
|
||||
return $host;
|
||||
}
|
||||
|
||||
protected function getPort()
|
||||
{
|
||||
if ($this->input->hasOption('port')) {
|
||||
$port = $this->input->getOption('port');
|
||||
} else {
|
||||
$port = !empty($this->config['port']) ? $this->config['port'] : 2345;
|
||||
}
|
||||
|
||||
return $port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\worker\command;
|
||||
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\input\Argument;
|
||||
use think\console\input\Option;
|
||||
use think\console\Output;
|
||||
use think\facade\App;
|
||||
use think\facade\Config;
|
||||
use think\worker\Http as HttpServer;
|
||||
|
||||
/**
|
||||
* Worker 命令行类
|
||||
*/
|
||||
class Worker extends Command
|
||||
{
|
||||
protected $config = [];
|
||||
|
||||
public function configure()
|
||||
{
|
||||
$this->setName('worker')
|
||||
->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
|
||||
->addOption('host', 'H', Option::VALUE_OPTIONAL, 'the host of workerman server.', null)
|
||||
->addOption('port', 'p', Option::VALUE_OPTIONAL, 'the port of workerman server.', null)
|
||||
->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.')
|
||||
->setDescription('Workerman HTTP Server for ThinkPHP');
|
||||
}
|
||||
|
||||
public function execute(Input $input, Output $output)
|
||||
{
|
||||
$action = $input->getArgument('action');
|
||||
|
||||
if (DIRECTORY_SEPARATOR !== '\\') {
|
||||
if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status', 'connections'])) {
|
||||
$output->writeln("<error>Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .</error>");
|
||||
return false;
|
||||
}
|
||||
|
||||
global $argv;
|
||||
array_shift($argv);
|
||||
array_shift($argv);
|
||||
array_unshift($argv, 'think', $action);
|
||||
} elseif ('start' != $action) {
|
||||
$output->writeln("<error>Not Support action:{$action} on Windows.</error>");
|
||||
return false;
|
||||
}
|
||||
|
||||
if ('start' == $action) {
|
||||
$output->writeln('Starting Workerman http server...');
|
||||
}
|
||||
|
||||
$this->config = Config::get('worker');
|
||||
|
||||
if (isset($this->config['context'])) {
|
||||
$context = $this->config['context'];
|
||||
unset($this->config['context']);
|
||||
} else {
|
||||
$context = [];
|
||||
}
|
||||
|
||||
$host = $this->getHost();
|
||||
$port = $this->getPort();
|
||||
|
||||
$worker = new HttpServer($host, $port, $context);
|
||||
|
||||
if (empty($this->config['pidFile'])) {
|
||||
$this->config['pidFile'] = App::getRootPath() . 'runtime/worker.pid';
|
||||
}
|
||||
|
||||
// 避免pid混乱
|
||||
$this->config['pidFile'] .= '_' . $port;
|
||||
|
||||
// 设置应用根目录
|
||||
$worker->setRootPath(App::getRootPath());
|
||||
|
||||
// 应用设置
|
||||
if (!empty($this->config['app_init'])) {
|
||||
$worker->appInit($this->config['app_init']);
|
||||
unset($this->config['app_init']);
|
||||
}
|
||||
|
||||
// 开启守护进程模式
|
||||
if ($this->input->hasOption('daemon')) {
|
||||
$worker->setStaticOption('daemonize', true);
|
||||
}
|
||||
|
||||
// 开启HTTPS访问
|
||||
if (!empty($this->config['ssl'])) {
|
||||
$this->config['transport'] = 'ssl';
|
||||
unset($this->config['ssl']);
|
||||
}
|
||||
|
||||
// 设置网站目录
|
||||
if (empty($this->config['root'])) {
|
||||
$this->config['root'] = App::getRootPath() . 'public';
|
||||
}
|
||||
|
||||
$worker->setRoot($this->config['root']);
|
||||
unset($this->config['root']);
|
||||
|
||||
// 设置文件监控
|
||||
if (DIRECTORY_SEPARATOR !== '\\' && (App::isDebug() || !empty($this->config['file_monitor']))) {
|
||||
$interval = $this->config['file_monitor_interval'] ?? 2;
|
||||
$paths = !empty($this->config['file_monitor_path']) ? $this->config['file_monitor_path'] : [App::getAppPath(), App::getConfigPath()];
|
||||
$worker->setMonitor($interval, $paths);
|
||||
unset($this->config['file_monitor'], $this->config['file_monitor_interval'], $this->config['file_monitor_path']);
|
||||
}
|
||||
|
||||
// 全局静态属性设置
|
||||
foreach ($this->config as $name => $val) {
|
||||
if (in_array($name, ['stdoutFile', 'daemonize', 'pidFile', 'logFile'])) {
|
||||
$worker->setStaticOption($name, $val);
|
||||
unset($this->config[$name]);
|
||||
}
|
||||
}
|
||||
|
||||
// 设置服务器参数
|
||||
$worker->option($this->config);
|
||||
|
||||
if (DIRECTORY_SEPARATOR == '\\') {
|
||||
$output->writeln('You can exit with <info>`CTRL-C`</info>');
|
||||
}
|
||||
|
||||
$worker->start();
|
||||
}
|
||||
|
||||
protected function getHost(string $default = '0.0.0.0')
|
||||
{
|
||||
if ($this->input->hasOption('host')) {
|
||||
$host = $this->input->getOption('host');
|
||||
} else {
|
||||
$host = !empty($this->config['host']) ? $this->config['host'] : $default;
|
||||
}
|
||||
|
||||
return $host;
|
||||
}
|
||||
|
||||
protected function getPort(string $default = '2346')
|
||||
{
|
||||
if ($this->input->hasOption('port')) {
|
||||
$port = $this->input->getOption('port');
|
||||
} else {
|
||||
$port = !empty($this->config['port']) ? $this->config['port'] : $default;
|
||||
}
|
||||
|
||||
return $port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
// +----------------------------------------------------------------------
|
||||
// | Workerman设置 仅对 php think worker:gateway 指令有效
|
||||
// +----------------------------------------------------------------------
|
||||
return [
|
||||
// 扩展自身需要的配置
|
||||
'protocol' => 'websocket', // 协议 支持 tcp udp unix http websocket text
|
||||
'host' => '0.0.0.0', // 监听地址
|
||||
'port' => 2348, // 监听端口
|
||||
'socket' => '', // 完整监听地址
|
||||
'context' => [], // socket 上下文选项
|
||||
'register_deploy' => true, // 是否需要部署register
|
||||
'businessWorker_deploy' => true, // 是否需要部署businessWorker
|
||||
'gateway_deploy' => true, // 是否需要部署gateway
|
||||
|
||||
// Register配置
|
||||
'registerAddress' => '127.0.0.1:1236',
|
||||
|
||||
// Gateway配置
|
||||
'name' => 'thinkphp',
|
||||
'count' => 1,
|
||||
'lanIp' => '127.0.0.1',
|
||||
'startPort' => 2000,
|
||||
'daemonize' => false,
|
||||
'pingInterval' => 30,
|
||||
'pingNotResponseLimit' => 0,
|
||||
'pingData' => '{"type":"ping"}',
|
||||
|
||||
// BusinsessWorker配置
|
||||
'businessWorker' => [
|
||||
'name' => 'BusinessWorker',
|
||||
'count' => 1,
|
||||
'eventHandler' => '\think\worker\Events',
|
||||
],
|
||||
|
||||
];
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
// +----------------------------------------------------------------------
|
||||
// | Workerman设置 仅对 php think worker:server 指令有效
|
||||
// +----------------------------------------------------------------------
|
||||
return [
|
||||
// 扩展自身需要的配置
|
||||
'protocol' => 'websocket', // 协议 支持 tcp udp unix http websocket text
|
||||
'host' => '0.0.0.0', // 监听地址
|
||||
'port' => 2345, // 监听端口
|
||||
'socket' => '', // 完整监听地址
|
||||
'context' => [], // socket 上下文选项
|
||||
'worker_class' => '', // 自定义Workerman服务类名 支持数组定义多个服务
|
||||
|
||||
// 支持workerman的所有配置参数
|
||||
'name' => 'thinkphp',
|
||||
'count' => 4,
|
||||
'daemonize' => false,
|
||||
'pidFile' => '',
|
||||
|
||||
// 支持事件回调
|
||||
// onWorkerStart
|
||||
'onWorkerStart' => function ($worker) {
|
||||
|
||||
},
|
||||
// onWorkerReload
|
||||
'onWorkerReload' => function ($worker) {
|
||||
|
||||
},
|
||||
// onConnect
|
||||
'onConnect' => function ($connection) {
|
||||
|
||||
},
|
||||
// onMessage
|
||||
'onMessage' => function ($connection, $data) {
|
||||
$connection->send('receive success');
|
||||
},
|
||||
// onClose
|
||||
'onClose' => function ($connection) {
|
||||
|
||||
},
|
||||
// onError
|
||||
'onError' => function ($connection, $code, $msg) {
|
||||
echo "error [ $code ] $msg\n";
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
// +----------------------------------------------------------------------
|
||||
// | Workerman设置 仅对 php think worker 指令有效
|
||||
// +----------------------------------------------------------------------
|
||||
return [
|
||||
// 扩展自身需要的配置
|
||||
'host' => '0.0.0.0', // 监听地址
|
||||
'port' => 2346, // 监听端口
|
||||
'root' => '', // WEB 根目录 默认会定位public目录
|
||||
'app_path' => '', // 应用目录 守护进程模式必须设置(绝对路径)
|
||||
'file_monitor' => false, // 是否开启PHP文件更改监控(调试模式下自动开启)
|
||||
'file_monitor_interval' => 2, // 文件监控检测时间间隔(秒)
|
||||
'file_monitor_path' => [], // 文件监控目录 默认监控application和config目录
|
||||
|
||||
// 支持workerman的所有配置参数
|
||||
'name' => 'thinkphp',
|
||||
'count' => 4,
|
||||
'daemonize' => false,
|
||||
'pidFile' => '',
|
||||
];
|
||||
Reference in New Issue
Block a user