分析了多种数据同步方式后,我们来试试 Soul 网关的集群模式。
首先我们使用 mvn clean intall && mvn clean package 来打出jar包,进入 soul-bootstrap/target,使用以下命令才启动多个 soul-bootstrap 服务:
java -jar soul-bootstrap.jar --server.port=8095
java -jar soul-bootstrap.jar --server.port=8096
java -jar soul-bootstrap.jar --server.port=8097
启动三个服务后,我们需要用 nginx 做下负载均衡。
使用 vim 编写配置文件(其中 soul.hazyrain.com 可以换成你喜欢的域名,在 hosts 文件上做好配置即可):
#配置upstream,注意这个后面的 bootstrap 是 alias,把他配置到location 那里
upstream bootstrap {
server localhost:8095 fail_timeout=3s max_fails=2;
server localhost:8096 fail_timeout=3s max_fails=2;
server localhost:8097 fail_timeout=3s max_fails=2;
#添加 ip hash,能将来自同一 IP 的客户端请求派发给同一个服务实例
ip_hash;
}
server {
listen 80;
server_name soul.hazyrain.com;
location / {
proxy_pass http://bootstrap;
}
}
执行 nginx -s reload
,更新配置。
尝试访问 soul.hazyrain.com:
OK,我们已经成功使用nginx 代理了 三个节点的 soul-bootstrap 集群。
现在我们来启动一个简单的 flask 应用,并在soul-admin 中配置对应规则:
调用 soul-admin 注册 http 服务的接口注册服务:
#POST请求:'http://localhost:9095/soul-client/springmvc-register'
{
"appName": "fake-api",
"context": "",
"path": "fake",
"rpcType": "http",
"host": "soul.hazyrain.com",
"port": 5000,
"ruleName": "fake",
"enabled": "true"
}
再调用 我们的nginx 代理集群的 endpoint:http://soul.hazyrain.com/fake/foo/bar
成功返回数据:
使用 postman 的 runner 做下测试,执行500次调用,查看调用结果:
{
"id": "789bccc1-f41c-45ee-8033-aff647a1fab0",
"name": "soul",
"timestamp": "2021-01-25T15:04:31.400Z",
"collection_id": "be2b94d5-ff96-484f-b7e0-23bda6d4d908",
"folder_id": 0,
"environment_id": "0",
"totalPass": 1000,
"totalFail": 0,
"results": [
{
"id": "266f5d02-bfbe-4a93-8679-7267c8d75cd8",
"name": "proxy test",
"time": 2,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {
"Status code is 200": true,
"Body matches string": true
},
"testPassFailCounts": {
"Status code is 200": {
"pass": 500,
"fail": 0
},
"Body matches string": {
"pass": 500,
"fail": 0
}
},
"times": [],//略
"allTests": [] //略
}
],
"count": 500,
"totalTime": 1675,
"collection": {
"requests": [
{
"id": "266f5d02-bfbe-4a93-8679-7267c8d75cd8",
"method": "GET"
}
]
}
}
由 count 和 totalTime 可以计算出,平均耗时为 3.35 毫秒,相当可观的数字。
总结
Soul 网关能够支撑多个网关节点做负载均衡,配置也可通过soul-admin 同步到所有节点上。同时 websocket 断开链接后,soul-bootstrap 也有重连的机制,相当可靠。