这篇文章主要介绍了关于利用swoole同时更新多台服务器的代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
一个小型网站的架构, 前面一台负载均衡, 后面几台web服务器. 更新代码成了难题, 一个一个FTP传不现实, 而且容易漏传,导致两个WEB服务器的代码都不一致.
一个简单的想法:
利用Websocket Server发送更新指令, Websocket Client 接收到更新指令, 运行git pull更新代码.
WebSocket Client有几个角色:
Solider: 接收命令, 不能发送命令
Commander: 发送命令
流程图:
![1530866733786852.png 4166444827-5b2875a1b3581_articlex[1].png](https://img.php.cn//upload/image/449/793/379/1530866733786852.png)
部分代码实现:
table = new Table();
$this->server = new WebSocketServer($config['host'], $config['port']);
$this->server->set($config['configuration']);
$this->addEventListener();
}
public function addEventListener()
{
$this->server->on('open', Closure::fromCallable([$this, 'onOpen']));
$this->server->on('message', Closure::fromCallable([$this, 'onMessage']));
$this->server->on('close', Closure::fromCallable([$this, 'onClose']));
}
private function onOpen($server, $request)
{
if ($request->get['role'] == 'commander') {
$this->table->commander = $request->fd;
} else {
$soliders = $this->table->soliders;
$soliders[] = $request->fd;
$this->table->soliders = $soliders;
}
}
private function onMessage($server, $frame)
{
if ($frame->fd == $this->table->commander) {
$command = $frame->data;
foreach ($this->table->soliders as $solider) {
$this->server->push($solider, $command);
}
} else {
$this->server->push($frame->fd, "You don not have any right to send message");
}
}
private function onClose($server, $fd)
{
$soliders = $this->table->soliders;
if (in_array($fd, $soliders)) {
unset($soliders[array_search($fd, $soliders)]);
}
}
public function run()
{
$this->server->start();
}
}
$server = new Server([
'host' => '0.0.0.0',
'port' => 8015,
'configuration' => [
'daemonize' => 1,
]
]);
$server->run(); $this->protocol, 'host' => $this->host, 'port' => $this->port, 'query' => $this->query) = parse_url($url);
if ($this->protocol == 'wss') {
echo 'unsupport protocol';
}
$this->client = new WebSocketClient($this->host, $this->port);
}
public function start(Callable $callback)
{
$this->client->upgrade('/?' . $this->query, $callback);
}
public function __set($field, $value)
{
if (in_array($field, $this->allow_events) && is_callable($value)) {
$this->client->on(strtolower(substr($field, 2)), $value);
} else {
echo 'Unsupport Event';
}
}
}onMessage = function($client, $frame) {
list('command' => $command, 'params' => $params) = parseCommand($frame->data);
echo $command;
switch ($command) {
case 'update':
updateCommand();
break;
}
};
$ws->onClose = function($client) {
};
$ws->start(function ($client) {
});
\Swoole\Process::daemon();
Document
完整代码:
https://gitee.com/shuizhuyu/P...
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:










