andreybolonin / ratchet-multi-instance
Ratchet 多实例
Requires
- php: >=7.1
- cboden/ratchet: ^0.4.1
- gos/websocket-client: ^0.1.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.11
- phpstan/phpstan: ^0.9.2
This package is not auto-updated.
Last update: 2024-09-18 20:18:38 UTC
README
0) 检查,你是否安装了高性能的 ext-event 扩展 (libevent)
http://socketo.me/docs/deploy#evented-io-extensions
https://github.com/reactphp/event-loop#exteventloop
https://www.pigo.idv.tw/archives/589
1) 定义你的池(config/services.yaml)
wampserver_broadcast: ['127.0.0.1:8095', '127.0.0.1:8097', '127.0.0.1:8099']
2) 排除此节点
$key = array_search($this->websocket_this_node, $this->wampserver_broadcast);
unset($this->wampserver_broadcast[$key]);
3) 运行你的节点
bin/console server:run --port=8095
bin/console server:run --port=8097
bin/console server:run --port=8099
4) 设置 NGINX(作为负载均衡器)
upstream socket { server 127.0.0.1:8095; server 127.0.0.1:8097; server 127.0.0.1:8099; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { server_name 127.0.0.1; listen 8090; proxy_next_upstream error; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header Host $http_host; location / { proxy_pass http://socket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_read_timeout 86400; # neccessary to avoid websocket timeout disconnect proxy_redirect off; } }
https://nginx.ac.cn/en/docs/http/load_balancing.html https://nginx.ac.cn/en/docs/http/websocket.html
安装
-
composer req andreybolonin/ratchet-multi-instance
-
在你的 Topic 类中注入
use RatchetMultiInstanceTrait;
-
在你的 Topic 类中添加
broadcast/channel
public function onPublish(ConnectionInterface $connection, $topic, $event, array $exclude, array $eligible) { switch ($topic->getId()) { case 'counter/channel': $this->CounterTopic($connection, $topic, $event, $exclude, $eligible); break; case 'price/channel': $this->PriceTopic($connection, $topic, $event, $exclude, $eligible); break; case 'broadcast/channel': $this->BroadcastTopic($connection, $topic, $event, $exclude, $eligible); break; } }
- 使用
$topic->broadcast($event)
和$this->broadcast($event)
发送广播到其他 WampServer 节点