.NET Core SignalR Redis底板详解(一)
生活随笔
收集整理的這篇文章主要介紹了
.NET Core SignalR Redis底板详解(一)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
其實(shí)微軟在.NET Framework時代就有Redis和Signalr的解決方案了。只不過我沒有花心思去找源碼。.NET Core版本的源碼倒是很全。我們在用signalR的時候。是會先創(chuàng)建一個ChatHub繼承Hub
public class ChatHub:Hub{public async Task SendMessage(string user,string message){await Clients.All.SendAsync("ReceiveMessage", user, message);}}可以看到這里是調(diào)用了Clients.All.SendAsync方法。我們查看源碼,可以看到Hub是一個抽象類
public abstract class Hub : IDisposable{private bool _disposed;private IHubCallerClients _clients;private HubCallerContext _context;private IGroupManager _groups;/// <summary>/// Gets or sets an object that can be used to invoke methods on the clients connected to this hub./// </summary>public IHubCallerClients Clients{get{CheckDisposed();return _clients;}set{CheckDisposed();_clients = value;}} }在Hub中的Clients繼承IHubCallerClients的。我們通過Crtl+F12查看實(shí)現(xiàn)找到HubCallerClients。所以不難看出上文中的Clients其實(shí)是HubCallerClients對象。在HubCallerClients中可以找到這段代碼
public IClientProxy All => _hubClients.All; 而這個_hubClients其實(shí)是HubClients。在HubClients的構(gòu)造函數(shù)中我們可以看到 public HubClients(HubLifetimeManager<THub> lifetimeManager){_lifetimeManager = lifetimeManager;All = new AllClientProxy<THub>(_lifetimeManager);} HubLifetimeManager是一個抽象類。在這里我們用Redis做底板的時候。在這段代碼里就完成了 HubLifetimeManager的注冊 public static ISignalRServerBuilder AddStackExchangeRedis(this ISignalRServerBuilder signalrBuilder, Action<RedisOptions> configure){signalrBuilder.Services.Configure(configure);signalrBuilder.Services.AddSingleton(typeof(HubLifetimeManager<>), typeof(RedisHubLifetimeManager<>));return signalrBuilder;}而這個AllClientProxy對象其實(shí)很干凈。只有一個方法
internal class AllClientProxy<THub> : IClientProxy where THub : Hub{private readonly HubLifetimeManager<THub> _lifetimeManager;public AllClientProxy(HubLifetimeManager<THub> lifetimeManager){_lifetimeManager = lifetimeManager;}public Task SendCoreAsync(string method, object[] args, CancellationToken cancellationToken = default){return _lifetimeManager.SendAllAsync(method, args);}}所以上面的Clients.All其實(shí)是AllClientProxy對象。至于SendAsync其實(shí)是一個擴(kuò)展方法
public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, CancellationToken cancellationToken = default){return clientProxy.SendCoreAsync(method, new[] { arg1, arg2 }, cancellationToken);}可以看到,此時Clients.All.SendAsync實(shí)際上是調(diào)用AllClientProxy的SendCoreAsync方法
轉(zhuǎn)載于:https://www.cnblogs.com/dbdn/p/11389737.html
總結(jié)
以上是生活随笔為你收集整理的.NET Core SignalR Redis底板详解(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 入门Mac快捷键详细分类整理,包括Ecl
- 下一篇: .NET Core SignalR Re