平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MqttWorker.cs 2.9 KiB

3 maanden geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Masuit.Tools;
  2. using NewLife.MQTT;
  3. using SafeCampus.Core;
  4. using SafeCampus.Cache;
  5. namespace SafeCampus.Background;
  6. /// <summary>
  7. /// mqtt̨
  8. /// </summary>
  9. public class MqttWorker : BackgroundService
  10. {
  11. private readonly ILogger<MqttWorker> _logger;
  12. private readonly ISimpleCacheService _simpleCacheService;
  13. private readonly MqttClient _mqtt;
  14. public MqttWorker(ILogger<MqttWorker> logger, ISimpleCacheService simpleCacheService, IMqttClientManager mqttClientManager)
  15. {
  16. _logger = logger;
  17. this._simpleCacheService = simpleCacheService;
  18. this._mqtt = mqttClientManager.GetClient();
  19. }
  20. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  21. {
  22. //豸
  23. await _mqtt.SubscribeAsync("$SYS/brokers/+/clients/+/+", (e) =>
  24. {
  25. var topicList = e.Topic.Split("/");///ָ
  26. var clientId = topicList[topicList.Length - 2];//ȡͻID
  27. if (clientId.Contains("_"))//жϿͻIDǷ»»߱ʾwebû¼
  28. {
  29. var userId = clientId.Split("_")[0];
  30. //ȡredisǰûtokenϢб
  31. var tokenInfos = _simpleCacheService.HashGetOne<List<TokenInfo>>(CacheConst.Cache_UserToken, userId);
  32. if (tokenInfos != null)
  33. {
  34. var connectEvent = topicList.Last();//ȡ¼ж߻
  35. if (connectEvent == "connected")//
  36. {
  37. _logger.LogInformation($"豸{clientId}");
  38. var token = _simpleCacheService.Get<string>(CacheConst.Cache_MqttClientUser + clientId);//ȡmqttͻIDӦûtoken
  39. if (token == null) return;//ûtokenֱ˳
  40. //ȡredisеǰtoken
  41. var tokenInfo = tokenInfos.Where(it => it.Token == token).FirstOrDefault();
  42. if (tokenInfo != null)
  43. {
  44. tokenInfo.ClientIds.Add(clientId);//ӵͻб
  45. _simpleCacheService.HashAdd(CacheConst.Cache_UserToken, userId, tokenInfos);//Redis
  46. }
  47. }
  48. else //
  49. {
  50. _logger.LogInformation($"豸{clientId}");
  51. //ȡǰͻIDڵtokenϢ
  52. var tokenInfo = tokenInfos.Where(it => it.ClientIds.Contains(clientId)).FirstOrDefault();
  53. if (tokenInfo != null)
  54. {
  55. tokenInfo.ClientIds.RemoveWhere(it => it == clientId);//ӿͻбɾ
  56. _simpleCacheService.HashAdd(CacheConst.Cache_UserToken, userId, tokenInfos);//Redis
  57. }
  58. }
  59. }
  60. }
  61. });
  62. }
  63. }