This commit is contained in:
Default
2025-03-20 21:10:55 +08:00
parent 62d2e78347
commit b09e4fca11
41 changed files with 1369 additions and 6258 deletions

View File

@@ -0,0 +1,27 @@
<?php
declare (strict_types = 1);
namespace minserver;
use think\Container;
use think\facade\Db;
class ProcessSanitizer
{
static public function reloadRedis()
{
Container::getInstance()->delete('cache');
}
static public function reloadDb()
{
Db::close();
Container::getInstance()->delete('think\DbManager');
}
static public function destructConnectSource()
{
self::reloadDb();
self::reloadRedis();
}
}

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace minserver;
use think\facade\Cache;
class QueueManage
{
public $strQueueName = '';
public function __construct($intIndex = 1, $strQueueName = '')
{
if ($strQueueName == '') {
$arrConfig = config('task.queue');
$strQueueName = $arrConfig[$intIndex]['name'];
}
$this->strQueueName = $strQueueName;
}
public function get()
{
return Cache::store('redis')->lpop($this->strQueueName);
}
public function set($arrData)
{
$strData = json_encode($arrData);
return Cache::store('redis')->rpush($this->strQueueName, $strData);
}
}

View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace minserver;
class Rout
{
static public function httpDispense(\Swoole\Http\Request $Request, \Swoole\Http\Response $Response)
{
$Response->status(999, 'Hei Guys ~');
$Response->header("Content-Type", "text/html; charset=utf-8");
$Response->end("<h1>Hello reptile~. #" . rand(1000, 9999) . "</h1>");
}
static public function tcpDispense(\Swoole\Server $server, $fd, $reactor_id, $mixedData) {}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace minserver;
use minserver\ProcessSanitizer;
class ScheduledTasks
{
static public function hander($arrProcessTask = [])
{
ProcessSanitizer::destructConnectSource();
call_user_func($arrProcessTask['callback'], $arrProcessTask['param']);
sleep($arrProcessTask['execution_interval']);
}
}

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace minserver;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\console\input\Option;
class ServerConsole extends Command
{
private $arrArguments = [
'action' => ['start', 'stop', 'restart', 'status',],
'daemonize' => ['d', "false",],
'forcibly' => ['f', "false",],
];
private $arrReflection = [
\minserver\ServerManage::class,
];
protected function configure()
{
$this->setName('php think task')
->addArgument('action', Argument::REQUIRED, "action: (" . implode('|', $this->arrArguments['action']) . ')')
->addOption('daemonize', 'd', Option::VALUE_NONE, "daemonize start service")
->addOption('forcibly', 'f', Option::VALUE_NONE, "ignore user forcibly start service")
->setDescription('swoole task server')
->setHelp('php think task <action> [-d] [-f] run server');
}
protected function checkUser(Input $Input)
{
if (!$Input->getOption('forcibly')) {
$strUser = get_current_user();
if ($strUser == 'root') {
$strError = sprintf("Sorry , Can't start service by [%s] user!,\n but you can add option '-f' forcibly start on you debug ,\n Do not use in production environment !!!!!!!!!",$strUser);
throw new \InvalidArgumentException($strError);
}
if ($strUser != 'www') {
throw new \InvalidArgumentException("Sorry , Can't start service by [{$strUser}] user!, please use [www] user !");
}
}
}
protected function execute(Input $Input, Output $Output)
{
$this->checkArguments(['action'], $Input, $Output);
$strAction = trim($Input->getArgument('action'));
if ($strAction == 'start' || $strAction == 'restart') {
$this->checkUser($Input);
}
$arrArgs = array_merge($Input->getArguments(), $Input->getOptions());
$this->{$strAction}($arrArgs);
}
private function checkArguments($arrArguments, Input $Input)
{
foreach ($arrArguments as $strArguments) {
$strVal = trim($Input->getArgument($strArguments));
if (!in_array($strVal, $this->arrArguments[$strArguments])) {
throw new \InvalidArgumentException("Arguments [{$strVal}] is not defined! Optional parameters [" . implode(' ', $this->arrArguments[$strArguments]) . "] !");
}
}
}
public function __call($strAction, $arrArguments)
{
foreach ($this->arrReflection as $strClass) {
if (method_exists($strClass, $strAction)) {
return call_user_func([new $strClass, $strAction], $arrArguments);
}
}
throw new \InvalidArgumentException("Action [{$strAction}] no method available! ");
}
}

View File

@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace minserver;
class ServerCore
{
private $arrConfig;
private static $obj;
private $Server;
static $Process = NULL;
static function instance($arrConfig)
{
if (self::$obj == null) {
self::$obj = new self($arrConfig);
}
return self::$obj;
}
public function __construct($arrConfig)
{
$this->arrConfig = $arrConfig;
$this->createServer();
}
private function serHttpConfig()
{
$this->Server->set($this->filterConfig());
$this->Server->on('request', [\minserver\Rout::class, 'httpDispense']);
}
private function filterConfig()
{
$arrConfig = $this->arrConfig;
unset($arrConfig['host']);
unset($arrConfig['port']);
unset($arrConfig['mode']);
unset($arrConfig['sockType']);
unset($arrConfig['server_type']);
return $arrConfig;
}
private function serTcpConfig()
{
$this->Server->set($this->filterConfig());
$this->Server->on('receive', [\minserver\Rout::class, 'tcpDispense']);
}
private function createServer()
{
switch ($this->arrConfig['server_type']) {
case 'HTTP':
$this->Server = new \Swoole\Http\Server($this->arrConfig['host'], $this->arrConfig['port']);
$this->serHttpConfig();
break;
default:
$this->Server = new \Swoole\Server($this->arrConfig['host'], $this->arrConfig['port'], $this->arrConfig['mode'], $this->arrConfig['sockType']);
$this->serTcpConfig();
break;
}
$this->Server->on('task', [$this, 'onTask']);
$this->Server->on('finish', [$this, 'onFinish']);
}
public function getServer()
{
return $this->Server;
}
public function onTask($Http, $task_id, $from_id, $arrData)
{
$mixedResult = call_user_func_array($arrData[0], $arrData[1]);
$Http->finish($mixedResult);
}
public function onFinish($Http, $task_id, $mixedData)
{
}
}

View File

@@ -0,0 +1,129 @@
<?php
declare(strict_types=1);
namespace minserver;
class ServerManage
{
static $HttpService;
static $arrDynamicConfig = [];
public function __init($arrArgvs = [])
{
$this->setConfigDaemonize($arrArgvs[0]['daemonize'] ?? 'false');
}
private function setConfigDaemonize($strMode)
{
self::$arrDynamicConfig['daemonize'] = (bool)$strMode;
}
private function getPid()
{
return file_exists(config('task.service.pid_file')) ? file_get_contents(config('task.service.pid_file')) : NULL;
}
public function start($arrArgvs = [])
{
$this->__init($arrArgvs);
$intPid = (int)$this->getPid();
if ($intPid > 0 && \Swoole\Process::kill($intPid, SIG_DFL)) {
echo " Service is \e[0;32mRunning\e[0m ! " . PHP_EOL;
exit;
}
echo " Execute the \e[0;32m start\e[0m command ...... " . PHP_EOL;
$this->createService();
$this->addProcessList();
$this->addScheduledTasks();
self::$HttpService->getServer()->start();
}
public function stop($arrArgvs = [])
{
$this->__init($arrArgvs);
$intPid = (int)$this->getPid();
if ($intPid <= 0) {
echo " Service is \e[0;31mStop\e[0m ! " . PHP_EOL;
} else {
echo " Execute the \e[0;32m stop\e[0m command ...... " . PHP_EOL;
\Swoole\Process::kill($intPid, SIGTERM);
echo " Service is \e[0;31mStop\e[0m ! " . PHP_EOL;
}
}
public function status($arrArgvs = [])
{
$this->__init($arrArgvs);
$intPid = (int)$this->getPid();
if ($intPid <= 0) {
echo " Service is \e[0;31mStop\e[0m ! " . PHP_EOL;
} else if (\Swoole\Process::kill($intPid, SIG_DFL)) {
echo " Service is \e[0;32mRunning\e[0m ! " . PHP_EOL;
} else {
echo " Service is \e[0;31mStop\e[0m ! " . PHP_EOL;
}
}
public function restart($arrArgvs = [])
{
$this->__init($arrArgvs);
$intPid = (int)$this->getPid();
if ($intPid <= 0) {
echo " \e[0;31m Get Pid Error\e[0m !" . PHP_EOL;
echo " Execute the \e[0;32m start\e[0m command ...... " . PHP_EOL;
$this->start();
} else {
echo " Execute the \e[0;32m restart\e[0m command ...... " . PHP_EOL;
\Swoole\Process::kill($intPid, SIGUSR1);
}
}
private function addScheduledTasks()
{
if (config('task.scheduled_tasks_pool')) {
foreach (config('task.scheduled_tasks_pool') as $arrProcessTask) {
if ($arrProcessTask['status']) {
$Process = new \Swoole\Process(function () use ($arrProcessTask) {
call_user_func([\minserver\ScheduledTasks::class, 'hander'], $arrProcessTask);
});
self::$HttpService->getServer()->addProcess($Process);
}
}
}
}
private function addProcessList()
{
if (config('task.process_pool')) {
foreach (config('task.process_pool') as $v) {
for ($i = 0; $i < $v['Num']; $i++) {
$Process = new \Swoole\Process($v['callback']);
self::$HttpService->getServer()->addProcess($Process);
}
}
}
}
private function createService()
{
$arrHttpServiceConfig = array_merge(config('task.service'), self::$arrDynamicConfig);
self::$HttpService = ServerCore::instance($arrHttpServiceConfig);
}
}