using Microsoft.Extensions.Hosting; using SJZY.Expand.ABP.Core; using SJZY.Track.Application.Contract.Events; using SJZY.Track.Application.Contract.Services; namespace SJZY.Track.Application.HostServices; public class RedisHostService : IHostedService { readonly IForewarningCacheService _forewarningCacheService; public RedisHostService(IForewarningCacheService forewarningCacheService) { _forewarningCacheService = forewarningCacheService; } // todo:redis一旦重启,订阅的频道就会丢失,需要重新订阅 public Task StartAsync(CancellationToken cancellationToken) { // 订阅频道 RedisHelper.Client.Subscribe(GetKey(), Subscribe); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { RedisHelper.Client.UnSubscribe(GetKey()); return Task.CompletedTask; } private void Subscribe(string message, object value) { if (value is string str) { // 暂时只处理一个事件,不做反序列化 //var instance = Newtonsoft.Json.JsonConvert.DeserializeObject(value as string); var instance = Newtonsoft.Json.JsonConvert.DeserializeObject(str); if (instance != null) { _forewarningCacheService.Clear(instance); } } } private string GetKey() { return $"{GlobalConst.PublishNotifyChannelKey}"; } }