平安校园
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.
 
 
 
 
 
 

87 lines
2.4 KiB

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