track/src/SJZY.Track.Application/HostServices/RedisHostService.cs
2024-09-29 10:34:38 +08:00

50 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<ModifyWarningEvent>(value as string);
var instance = Newtonsoft.Json.JsonConvert.DeserializeObject<ClearRulCacheEvent>(str);
if (instance != null)
{
_forewarningCacheService.Clear(instance);
}
}
}
private string GetKey()
{
return $"{GlobalConst.PublishNotifyChannelKey}";
}
}