微信公眾號(hào):Dotnet9酥泛,網(wǎng)站:Dotnet9,問(wèn)題或建議:請(qǐng)網(wǎng)站留言嫌拣,
如果對(duì)您有所幫助:歡迎贊賞柔袁。
使用SignalR從服務(wù)端主動(dòng)推送警報(bào)日志到各種終端(桌面、移動(dòng)异逐、網(wǎng)頁(yè))
閱讀導(dǎo)航
- 本文背景
- 代碼實(shí)現(xiàn)
- 本文參考
1.本文背景
工作上有個(gè)業(yè)務(wù)捶索,.Net Core WebAPI作為服務(wù)端,需要將運(yùn)行過(guò)程中產(chǎn)生的日志分類灰瞻,并實(shí)時(shí)推送到各種終端進(jìn)行報(bào)警腥例,終端有桌面(WPF)、移動(dòng)(Xamarin.Forms)酝润、網(wǎng)站(Angular.JS)等燎竖,使用SignalR進(jìn)行警報(bào)日志推送。
下面是桌面端的測(cè)試效果:
2.代碼實(shí)現(xiàn)
整個(gè)系統(tǒng)由服務(wù)端袍祖、桌面端底瓣、網(wǎng)站、移動(dòng)端組成,結(jié)構(gòu)如下:
2.1 服務(wù)端與客戶端都使用的日志實(shí)體類
簡(jiǎn)單的日志定義捐凭,服務(wù)端會(huì)主動(dòng)將最新日志通過(guò)AlarmLogItem實(shí)例推送到各個(gè)終端:
/// <summary>
/// 報(bào)警日志
/// </summary>
public class AlarmLogItem
{
public string Id { get; set; }
/// <summary>
/// 日志類型
/// </summary>
public AlarmLogType Type { get; set; }
/// <summary>
/// 日志名稱
/// </summary>
public string Text { get; set; }
/// <summary>
/// 日志詳細(xì)信息
/// </summary>
public string Description { get; set; }
/// <summary>
/// 日志更新時(shí)間
/// </summary>
public string UpdateTime { get; set; }
}
public enum AlarmLogType
{
Info,
Warn,
Error
}
2.2 服務(wù)端
使用 .Net Core 2.2 搭建的Web API項(xiàng)目
2.2.1 集線器類AlarmLogHub.cs
定義集線器Hub類AlarmLogHub拨扶,繼承自Hub,用于SignalR通信茁肠,看下面的代碼患民,沒(méi)加任何方法,您沒(méi)看錯(cuò):
public class AlarmLogHub : Hub
{}
2.2.2 Startup.cs
需要在此類中注冊(cè)SignalR管道及服務(wù)垦梆,在下面兩個(gè)關(guān)鍵方法中用到匹颤,B/S后端的朋友非常熟悉了。
- ConfigureServices方法
添加SignalR管道(是這個(gè)說(shuō)法吧托猩?):
services.AddSignalR(options => { options.EnableDetailedErrors = true; });
- Configure方法注冊(cè)SignalR服務(wù)地址
端口用的8022印蓖,客戶端訪問(wèn)地址是:http://localhost:8022/alarmlog
app.UseSignalR(routes =>
{
routes.MapHub<AlarmLogHub>("/alarmlog");
});
2.2.3 SignalRTimedHostedService.cs
這是個(gè)關(guān)鍵類,用于服務(wù)端主動(dòng)推送日志使用京腥,Baidu赦肃、Google好久才找到,站長(zhǎng)技術(shù)棧以C/S為主公浪,B/S做的不多他宛,沒(méi)人指點(diǎn),心酸欠气,參考網(wǎng)址:How do I push data from hub to client every second using SignalR
厅各。
該類繼承自IHostedService,作為服務(wù)自啟動(dòng)(亂說(shuō)的)预柒,通過(guò)SignalRTimedHostedService 的構(gòu)造函數(shù)依賴注入得到IHubContext<AlarmLogHub>的實(shí)例队塘,用于服務(wù)端向各客戶端推送日志使用(在StartAsync方法中開(kāi)啟定時(shí)器,模擬服務(wù)端主動(dòng)推送警報(bào)日志卫旱,見(jiàn) DoWork 方法):
internal class SignalRTimedHostedService : IHostedService, IDisposable
{
private readonly IHubContext<AlarmLogHub> _hub;
private Timer _timer;
//模擬發(fā)送報(bào)警日志
List<AlarmLogItem> lstLogs = new List<AlarmLogItem> {
new AlarmLogItem{ Type=AlarmLogType.Error,Text="OK WebSocket斷連",Description="嘗試連接50次人灼,未成功重連!"},
new AlarmLogItem{ Type=AlarmLogType.Warn,Text="OK WebSocket斷開(kāi)重連",Description="嘗試連接5次顾翼,成功重連投放!"},
new AlarmLogItem{ Type=AlarmLogType.Warn,Text="OK Restfull斷連",Description="嘗試連接30次,成功重連适贸!"},
new AlarmLogItem{ Type=AlarmLogType.Error,Text="OK WebSocket斷連",Description="第一次斷開(kāi)鏈接灸芳!"},
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服務(wù)(繼承自 IHostedService),需要在Startup.cs的ConfigureServices方法中注冊(cè)管道(是吧蕊肥?各位有沒(méi)有B/S比較好的書(shū)籍推薦谒获,站長(zhǎng)打算有空好好學(xué)學(xué)):
services.AddHostedService<SignalRTimedHostedService>();
服務(wù)端關(guān)鍵代碼已經(jīng)全部奉上蛤肌,下面主要說(shuō)說(shuō)桌面端和移動(dòng)端代碼,其實(shí)兩者代碼類似批狱。
2.3 網(wǎng)站
參考 index.html
2.4 桌面端(WPF)
使用 .Net Core 3.0創(chuàng)建的WFP工程裸准,需要引入Nuget包:Microsoft.AspNetCore.SignalR.Client
界面用一個(gè)ListView展示收到的日志:
<Grid>
<ListBox x:Name="messagesList" RenderTransformOrigin="-0.304,0.109" BorderThickness="1" BorderBrush="Gainsboro"/>
</Grid>
后臺(tái)寫(xiě)的簡(jiǎn)陋,直接在窗體構(gòu)造函數(shù)中連接服務(wù)端SignalR地址:http://localhost:8022/alarmlog赔硫, 監(jiān)聽(tīng)服務(wù)端警報(bào)日志推送: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);
}
}
}
}
2.4 移動(dòng)端
移動(dòng)端其實(shí)和桌面端類似,因?yàn)樽烂娑耸褂玫?.Net Core 3.0爪膊,移動(dòng)端使用的 .NET Standard 2.0权悟,都需要引入Nuget包:Microsoft.AspNetCore.SignalR.Client。
界面使用ListView展示日志推盛,這就不貼代碼了峦阁,使用的MVVM方式,直接貼ViewModel代碼吧耘成,大家只看個(gè)大概拇派,不要糾結(jié)具體代碼,參照桌面.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>
/// 報(bào)警日志VM
/// </summary>
public class AlarmItemsViewModel : BaseViewModel
{
private ViewState _state = ViewState.Disconnected;
/// <summary>
/// 報(bào)警日志列表
/// </summary>
public ObservableCollection<AlarmLogItem> AlarmItems { get; set; }
public Command LoadItemsCommand { get; set; }
//連接報(bào)警服務(wù)端
private HubConnection _connection;
public AlarmItemsViewModel()
{
Title = "報(bào)警日志";
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, "添加項(xiàng)", 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
}
}
}
關(guān)鍵代碼已經(jīng)貼完了疮方,希望對(duì)大家能有所幫助控嗜。
3.參考
- .NET 客戶端 SignalR ASP.NET Core
- SignalR-samples
- How do I push data from hub to client every second using SignalR
除非注明,文章均由 Dotnet9 整理發(fā)布骡显,歡迎轉(zhuǎn)載疆栏。
轉(zhuǎn)載請(qǐng)注明本文地址:https://dotnet9.com/6913.html
歡迎掃描下方二維碼關(guān)注 Dotnet9 的微信公眾號(hào),本站會(huì)及時(shí)推送最新技術(shù)文章