体验用yarp连接websocket
前段时间一看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
欢迎大佬们一起完善~~