記錄Ocelot + SignalR 多服務端測試


前言

分兩個項目,一個Gatway,一個SignalR

貼代碼

1、Gatway

1、引用Ocelot

2、添加一點點代碼

Startup.cs

1556437515322

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

1556438762257

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

1556439019364

測試

1、啟動三個Signalr

1556439429156

2、啟動Gateway項目

1556439528846

3、啟動客戶端

新開三個客戶端,發現分配到了三個地址。

1556439986904

1556440027608

1556440052484

也就是意味着這三個連這不同的服務端,發信息應該是不通的。這里我們測試一下。

1556440286466

那再開兩個客戶端試試

1556440349057

1556440389987

不小心發了個54的消息,我們看下之前的54有沒有消息。

確實有。

1556440437045

4、測試結束

好了,測試完了。也沒看Ocelot源碼。

結論就是Ocelot這樣連SignalR都是各玩個的。這樣不能一起愉快的玩耍的。

所以使用其他的方式實現一下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM