前言 分兩個項目,一個Gatway,一個SignalR 貼代碼 1、Gatway 1、引用Ocelot 2、添加一點點代碼 Startup.cs 3、簡單配置ocelot ocelot.json 2、signalr 1、Startup.cs 2、chat.js 3、Program.cs 測試 1、啟 ...
前言
分兩個項目,一個Gatway,一個SignalR
貼代碼
1、Gatway
1、引用Ocelot
2、添加一點點代碼
Startup.cs
3、簡單配置ocelot
ocelot.json
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/{catchAll}", //下游路徑
"DownstreamScheme": "ws", //https //下游協議
"DownstreamHostAndPorts": [ // 下游主機及埠
{
"Host": "127.0.0.1", // 這裡是我後面signalr地址
"Port": 53353
},
{
"Host": "127.0.0.1",
"Port": 53354
},
{
"Host": "127.0.0.1",
"Port": 53355
}
],
"UpstreamPathTemplate": "/gateway/{catchAll}", // 上游路徑
"UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ], //上游使用的http方法
"LoadBalancerOptions": {
"Type": "RoundRobin" //雨露均沾
//LeastConnection 任務少的接客
//NoLoadBalance 天將降大任於斯人也
}
}
],
"GlobalConfiguration": { //全局配置
"BaseUrl": "http://127.0.0.1:5000"
}
}
2、signalr
1、Startup.cs
2、chat.js
//const connection = new signalR.HubConnectionBuilder()
// .withUrl("http://127.0.0.1:5000/gateway/chatHub") // 這裡使用http
// .configureLogging(signalR.LogLevel.Information)
// .build();
const connection = new signalR.HubConnectionBuilder()
.withUrl("ws://127.0.0.1:5000/gateway/chatHub", { // 這裡使用WebSockets,不這樣寫連不上的
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.configureLogging(signalR.LogLevel.Trace)
.build();
connection.on("ReceiveMessage", (user, message) => {
const encodedMsg = user + " says " + message;
const li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
document.getElementById("sendButton").addEventListener("click", event => {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
event.preventDefault();
});
connection.start().catch(err => console.error(err.toString()));
3、Program.cs
測試
1、啟動三個Signalr
2、啟動Gateway項目
3、啟動客戶端
新開三個客戶端,發現分配到了三個地址。
也就是意味著這三個連這不同的服務端,發信息應該是不通的。這裡我們測試一下。
那再開兩個客戶端試試
不小心發了個54的消息,我們看下之前的54有沒有消息。
確實有。
4、測試結束
好了,測試完了。也沒看Ocelot源碼。
結論就是Ocelot這樣連SignalR都是各玩個的。這樣不能一起愉快的玩耍的。
所以使用其他的方式實現一下。