前段時間一看yarp的倉庫,wow,終於釋出1.0版本了。.net也升級到6版本了,之前一直只是用yarp做HTTP轉發,今天剛好試試websocket
話不多說,直接開搞
配置叢集
首先先配置叢集資訊,必填的有
名稱
均衡負責策略
叢集列表,叢集Destinations可以配置多個。
配置路由
重點來了,配置路由轉發,需要將HTTP請求升級到WebSocket連結。
這個配置就比正常的Transforms多一點點
除了要新增PathPattern匹配轉發規則以外
還需要配置RequestHeader,將請求Upgrade成Websocket
如下圖配置
來來開始測試
建個最簡單SignalR服務
建個TestHub
using Microsoft.AspNetCore.SignalR;
namespace TestSinganlR
{
public class TestHub : Hub
{
public override Task OnConnectedAsync()
{
Console.WriteLine("````````````````````````````````");
Console.WriteLine("``````````OnConnected```````````");
Console.WriteLine("````````````````````````````````");
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception? exception)
{
Console.WriteLine("````````````````````````````````");
Console.WriteLine("``````````OnDisconnected```````````");
Console.WriteLine("````````````````````````````````");
return base.OnDisconnectedAsync(exception);
}
}
}
順便提一下.net6新建的web模板真簡潔,startup.cs檔案都不需要了
配置host,主要新增signalr和websocket支援
using Microsoft.AspNetCore.WebSockets;
using TestSinganlR;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureServices(services => {
services.AddSignalR();
services.AddWebSockets(options => {
});
}
);
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseWebSockets();
app.MapRazorPages();
app.MapHub<TestHub>("testhub");
app.Run();
建個簡單的Console Signalr Client
.net6裡面連console模板的main函式都不需要,牛皮。
直接就可以寫程式碼
using Microsoft.AspNetCore.SignalR.Client;
var connection = new HubConnectionBuilder()
.WithUrl("http://127.0.0.1:5000/hub/testhub", options => {
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets;
options.SkipNegotiation = true;
})
.WithAutomaticReconnect()
.Build();
await connection.StartAsync();
Thread.Sleep(int.MaxValue);
啟動服務,開測
yarp
signalR
啟動console
這時候signalr的控制檯輸出OnConnected了,說明正確連上了~~
關閉console
這時候signalr的控制檯輸出OnDisconnected了,說明連線斷開了~~
再來看看yarp控制檯輸出
搞定~
再順便推推自己封裝yarp的一個EFCore儲存庫和配置介面
上面配置的圖片就是yarp的配置介面,配置資訊儲存在資料庫支援熱更新
簡單無腦上手hhhhh~
倉庫地址是這個ReverseProxy.Store
歡迎大佬們一起完善~~