提交
This commit is contained in:
45
app/service/SwooleService.php
Normal file
45
app/service/SwooleService.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
namespace app\service;
|
||||
|
||||
use Swoole\Client;
|
||||
|
||||
class SwooleService
|
||||
{
|
||||
private static ?self $instance = null;
|
||||
private Client $client;
|
||||
private string $host = '127.0.0.1';
|
||||
private int $port = 9502;
|
||||
private float $timeout = 0.5;
|
||||
|
||||
// 私有化构造函数
|
||||
private function __construct()
|
||||
{
|
||||
$this->client = new Client(SWOOLE_SOCK_TCP);
|
||||
if (!$this->client->connect($this->host, $this->port, $this->timeout)) {
|
||||
throw new \RuntimeException("Cannot connect to Swoole Server {$this->host}:{$this->port}");
|
||||
}
|
||||
}
|
||||
|
||||
// 获取单例
|
||||
public static function getInstance(): self
|
||||
{
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
// 发送任务
|
||||
public function sendTask(array $task): bool
|
||||
{
|
||||
$data = json_encode($task) . "\r\n";
|
||||
return $this->client->send($data);
|
||||
}
|
||||
|
||||
// 关闭连接
|
||||
public function close(): void
|
||||
{
|
||||
$this->client->close();
|
||||
self::$instance = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user