|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- using Masuit.Tools;
- using NewLife.MQTT;
- using SafeCampus.Core;
- using SafeCampus.Cache;
-
- namespace SafeCampus.Background;
-
- /// <summary>
- /// mqtt̨
- /// </summary>
- public class MqttWorker : BackgroundService
- {
- private readonly ILogger<MqttWorker> _logger;
- private readonly ISimpleCacheService _simpleCacheService;
- private readonly MqttClient _mqtt;
-
- public MqttWorker(ILogger<MqttWorker> logger, ISimpleCacheService simpleCacheService, IMqttClientManager mqttClientManager)
- {
- _logger = logger;
- this._simpleCacheService = simpleCacheService;
- this._mqtt = mqttClientManager.GetClient();
- }
-
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- //豸
- await _mqtt.SubscribeAsync("$SYS/brokers/+/clients/+/+", (e) =>
- {
- var topicList = e.Topic.Split("/");///ָ
- var clientId = topicList[topicList.Length - 2];//ȡͻID
- if (clientId.Contains("_"))//жϿͻIDǷ»»߱ʾwebû¼
- {
- var userId = clientId.Split("_")[0];
- //ȡredisǰûtokenϢб
- var tokenInfos = _simpleCacheService.HashGetOne<List<TokenInfo>>(CacheConst.Cache_UserToken, userId);
- if (tokenInfos != null)
- {
- var connectEvent = topicList.Last();//ȡ¼ж
- if (connectEvent == "connected")//
- {
- _logger.LogInformation($"豸{clientId}");
- var token = _simpleCacheService.Get<string>(CacheConst.Cache_MqttClientUser + clientId);//ȡmqttͻIDӦûtoken
- if (token == null) return;//ûtokenֱ˳
- //ȡredisеǰtoken
- var tokenInfo = tokenInfos.Where(it => it.Token == token).FirstOrDefault();
- if (tokenInfo != null)
- {
- tokenInfo.ClientIds.Add(clientId);//ӵͻб
- _simpleCacheService.HashAdd(CacheConst.Cache_UserToken, userId, tokenInfos);//Redis
- }
- }
- else //
- {
- _logger.LogInformation($"豸{clientId}");
- //ȡǰͻIDڵtokenϢ
- var tokenInfo = tokenInfos.Where(it => it.ClientIds.Contains(clientId)).FirstOrDefault();
- if (tokenInfo != null)
- {
- tokenInfo.ClientIds.RemoveWhere(it => it == clientId);//ӿͻбɾ
- _simpleCacheService.HashAdd(CacheConst.Cache_UserToken, userId, tokenInfos);//Redis
- }
- }
- }
- }
- });
- }
- }
|