閱讀導航git
工做上有個業務,.Net Core WebAPI做爲服務端,須要將運行過程當中產生的日誌分類,並實時推送到各類終端進行報警,終端有桌面(WPF)、移動(Xamarin.Forms)、網站(Angular.JS)等,使用SignalR進行警報日誌推送。github
下面是桌面端的測試效果:
c#
整個系統由服務端、桌面端、網站、移動端組成,結構以下:
後端
簡單的日誌定義,服務端會主動將最新日誌經過AlarmLogItem實例推送到各個終端:微信
/// <summary> /// 報警日誌 /// </summary> public class AlarmLogItem { public string Id { get; set; } /// <summary> /// 日誌類型 /// </summary> public AlarmLogType Type { get; set; } /// <summary> /// 日誌名稱 /// </summary> public string Text { get; set; } /// <summary> /// 日誌詳細信息 /// </summary> public string Description { get; set; } /// <summary> /// 日誌更新時間 /// </summary> public string UpdateTime { get; set; } } public enum AlarmLogType { Info, Warn, Error }
使用 .Net Core 2.2 搭建的Web API項目app
定義集線器Hub類AlarmLogHub,繼承自Hub,用於SignalR通訊,看下面的代碼,沒加任何方法,您沒看錯:dom
public class AlarmLogHub : Hub {}
須要在此類中註冊SignalR管道及服務,在下面兩個關鍵方法中用到,B/S後端的朋友很是熟悉了。async
添加SignalR管道(是這個說法吧?):函數
services.AddSignalR(options => { options.EnableDetailedErrors = true; });
端口用的8022,客戶端訪問地址是:http://localhost:8022/alarmlog
app.UseSignalR(routes => { routes.MapHub<AlarmLogHub>("/alarmlog"); });
這是個關鍵類,用於服務端主動推送日誌使用,Baidu、Google很久才找到,站長技術棧以C/S爲主,B/S作的很少,沒人指點,心酸,參考網址:How do I push data from hub to client every second using SignalR。
該類繼承自IHostedService,做爲服務自啓動(亂說的),經過SignalRTimedHostedService 的構造函數依賴注入獲得IHubContext<AlarmLogHub>的實例,用於服務端向各客戶端推送日誌使用(在StartAsync方法中開啓定時器,模擬服務端主動推送警報日誌,見 DoWork 方法):
internal class SignalRTimedHostedService : IHostedService, IDisposable { private readonly IHubContext<AlarmLogHub> _hub; private Timer _timer; //模擬發送報警日誌 List<AlarmLogItem> lstLogs = new List<AlarmLogItem> { new AlarmLogItem{ Type=AlarmLogType.Error,Text="OK WebSocket斷連",Description="嘗試鏈接50次,未成功重連!"}, new AlarmLogItem{ Type=AlarmLogType.Warn,Text="OK WebSocket斷開重連",Description="嘗試鏈接5次,成功重連!"}, new AlarmLogItem{ Type=AlarmLogType.Warn,Text="OK Restfull斷連",Description="嘗試鏈接30次,成功重連!"}, new AlarmLogItem{ Type=AlarmLogType.Error,Text="OK WebSocket斷連",Description="第一次斷開連接!"}, new AlarmLogItem{ Type=AlarmLogType.Info,Text="OK WebSocket鏈接成功",Description="首次成功鏈接!"}, new AlarmLogItem{ Type=AlarmLogType.Error,Text="OK WebSocket斷連",Description="嘗試鏈接第7次,未成功重連!"} }; Random rd = new Random(DateTime.Now.Millisecond); public SignalRTimedHostedService(IHubContext<AlarmLogHub> hub) { _hub = hub; } public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(1)); return Task.CompletedTask; } private void DoWork(object state) { if (DateTime.Now.Second % rd.Next(1, 3) == 0) { AlarmLogItem log = lstLogs[rd.Next(lstLogs.Count)]; log.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); _hub.Clients.All.SendAsync("ReceiveAlarmLog", log); } } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } }
SignalRTimedHostedService 類做爲Host服務(繼承自 IHostedService),須要在Startup.cs的ConfigureServices方法中註冊管道(是吧?各位有沒有B/S比較好的書籍推薦,站長打算有空好好學學):
services.AddHostedService<SignalRTimedHostedService>();
服務端關鍵代碼已經所有奉上,下面主要說說桌面端和移動端代碼,其實二者代碼相似。
參考 index.html
使用 .Net Core 3.0建立的WFP工程,須要引入Nuget包:Microsoft.AspNetCore.SignalR.Client
界面用一個ListView展現收到的日誌:
<Grid> <ListBox x:Name="messagesList" RenderTransformOrigin="-0.304,0.109" BorderThickness="1" BorderBrush="Gainsboro"/> </Grid>
後臺寫的簡陋,直接在窗體構造函數中鏈接服務端SignalR地址:http://localhost:8022/alarmlog, 監聽服務端警報日誌推送:ReceiveAlarmLog。
using AppClient.Models; using Microsoft.AspNetCore.SignalR.Client; using System; using System.Threading.Tasks; using System.Windows; namespace SignalRChatClientCore { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { HubConnection connection; public MainWindow() { InitializeComponent(); connection = new HubConnectionBuilder() .WithUrl("http://localhost:8022/alarmlog") .Build(); connection.Closed += async (error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.On<AlarmLogItem>("ReceiveAlarmLog", (message) => { this.Dispatcher.Invoke(() => { messagesList.Items.Add(message.Description); }); }); try { connection.StartAsync(); messagesList.Items.Add("Connection started"); } catch (Exception ex) { messagesList.Items.Add(ex.Message); } } } }
移動端其實和桌面端相似,由於桌面端使用的 .Net Core 3.0,移動端使用的 .NET Standard 2.0,都須要引入Nuget包:Microsoft.AspNetCore.SignalR.Client。
界面使用ListView展現日誌,這就不貼代碼了,使用的MVVM方式,直接貼ViewModel代碼吧,你們只看個大概,不要糾結具體代碼,參照桌面.cs代碼,是否是同樣的?
using AppClient.Models; using AppClient.Views; using Microsoft.AspNetCore.SignalR.Client; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Threading.Tasks; using Xamarin.Forms; using System.Linq; namespace AppClient.ViewModels { /// <summary> /// 報警日誌VM /// </summary> public class AlarmItemsViewModel : BaseViewModel { private ViewState _state = ViewState.Disconnected; /// <summary> /// 報警日誌列表 /// </summary> public ObservableCollection<AlarmLogItem> AlarmItems { get; set; } public Command LoadItemsCommand { get; set; } //鏈接報警服務端 private HubConnection _connection; public AlarmItemsViewModel() { Title = "報警日誌"; AlarmItems = new ObservableCollection<AlarmLogItem>(); LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand()); //收到登陸成功通知 MessagingCenter.Subscribe<LoginViewModel, LoginUser>(this, "LoginSuccess", async (sender, userInfo) => { //DisplayAlert("登陸成功", userInfo.UserName, "肯定"); }); MessagingCenter.Subscribe<NewItemPage, AlarmLogItem>(this, "添加項", async (obj, item) => { var newItem = item as AlarmLogItem; AlarmItems.Add(newItem); await DataStore.AddItemAsync(newItem); }); ConnectAlarmServer(); } async Task ExecuteLoadItemsCommand() { if (IsBusy) return; IsBusy = true; try { AlarmItems.Clear(); var items = await DataStore.GetItemsAsync(true); foreach (var item in items) { AlarmItems.Add(item); } } catch (Exception ex) { Debug.WriteLine(ex); } finally { IsBusy = false; } } private async Task ConnectAlarmServer() { if (_state == ViewState.Connected) { try { await _connection.StopAsync(); } catch (Exception ex) { return; } _state = ViewState.Disconnected; } else { try { _connection = new HubConnectionBuilder() .WithUrl(App.Setting.AlarmHost) .Build(); _connection.On<AlarmLogItem>("ReceiveAlarmLog", async (newItem) => { AlarmItems.Add(newItem); await DataStore.AddItemAsync(newItem); }); _connection.Closed += async (error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await _connection.StartAsync(); }; await _connection.StartAsync(); } catch (Exception ex) { return; } _state = ViewState.Connected; } } private enum ViewState { Disconnected, Connecting, Connected, Disconnecting } } }
關鍵代碼已經貼完了,但願對你們能有所幫助。
除非註明,文章均由 Dotnet9 整理髮布,歡迎轉載。
轉載請註明本文地址:https://dotnet9.com/6913.html
歡迎掃描下方二維碼關注 Dotnet9 的微信公衆號,本站會及時推送最新技術文章