平安校园
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

NoticeEventSubscriber.cs 2.4 KiB

4 månader sedan
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 
  2. //
  3. namespace SafeCampus.System;
  4. /// <summary>
  5. /// 通知事件总线
  6. /// </summary>
  7. public class NoticeEventSubscriber : IEventSubscriber, ISingleton
  8. {
  9. private readonly ISimpleCacheService _simpleCacheService;
  10. private readonly IServiceScopeFactory _scopeFactory;
  11. private readonly SqlSugarScope _db;
  12. public NoticeEventSubscriber(ISimpleCacheService simpleCacheService, IServiceScopeFactory scopeFactory)
  13. {
  14. _db = DbContext.DB;
  15. _simpleCacheService = simpleCacheService;
  16. _scopeFactory = scopeFactory;
  17. }
  18. /// <summary>
  19. /// 通知用户下线事件
  20. /// </summary>
  21. /// <param name="context"></param>
  22. /// <returns></returns>
  23. [EventSubscribe(EventSubscriberConst.USER_LOGIN_OUT)]
  24. public async Task UserLoginOut(EventHandlerExecutingContext context)
  25. {
  26. var loginEvent = (UserLoginOutEvent)context.Source.Payload;//获取参数
  27. //客户端ID列表
  28. var clientIds = new List<string>();
  29. //遍历token列表获取客户端ID列表
  30. loginEvent.TokenInfos.ForEach(it =>
  31. {
  32. clientIds.AddRange(it.ClientIds);
  33. });
  34. }
  35. /// <summary>
  36. /// 有新的消息
  37. /// </summary>
  38. /// <param name="context"></param>
  39. /// <returns></returns>
  40. [EventSubscribe(EventSubscriberConst.NEW_MESSAGE)]
  41. public async Task NewMessage(EventHandlerExecutingContext context)
  42. {
  43. var newMessageEvent = (NewMessageEvent)context.Source.Payload;//获取参数
  44. var clientIds = new List<string>();
  45. //获取用户token列表
  46. var tokenInfos = _simpleCacheService.HashGet<List<TokenInfo>>(CacheConst.CACHE_USER_TOKEN, newMessageEvent.UserIds.ToArray());
  47. tokenInfos.ForEach(it =>
  48. {
  49. if (it != null)
  50. {
  51. it = it.Where(it => it.TokenTimeout > DateTime.Now).ToList();//去掉登录超时的
  52. //遍历token
  53. it.ForEach(it =>
  54. {
  55. clientIds.AddRange(it.ClientIds);//添加到客户端ID列表
  56. });
  57. }
  58. });
  59. }
  60. /// <summary>
  61. /// 获取服务
  62. /// </summary>
  63. /// <typeparam name="T"></typeparam>
  64. /// <returns></returns>
  65. private T GetService<T>() where T : class, new()
  66. {
  67. // 创建新的作用域
  68. using var scope = _scopeFactory.CreateScope();
  69. return scope.ServiceProvider.GetRequiredService<T>();
  70. }
  71. }