当前位置: 首页 > news >正文

[ABP实战开源项目]---ABP实时服务-通知系统.发布模式

简介

在ABP中,提供了通知服务。它是一个基于实时通知的基础设施。分为订阅模式和发布模式。
本次会在项目中使用发布模式来演示一个用户注册后,收到的欢迎信息。

发布模式

首先我们在领域层建立“INotificationManager”接口和“NotificationManager”实现类,如下:

 /// <summary>
    /// 通知管理领域服务
    /// </summary>
    public interface INotificationManager
    {
        Task WelcomeToCmsAsync(User user);
    }
   public class NotificationManager : CmsDomainServiceBase, INotificationManager
    {
        private readonly INotificationPublisher _notificationPublisher;
        public NotificationManager(INotificationPublisher notificationPublisher)
        {
            _notificationPublisher = notificationPublisher;
        }
        public async Task WelcomeToCmsAsync(User user)
        {
              await _notificationPublisher.PublishAsync(
                CmsConsts.NotificationConstNames.WelcomeToCms,
                new MessageNotificationData(L("WelcomeToCms")),severity:NotificationSeverity.Success,userIds:new []{user.ToUserIdentifier()}

        }      
 
    }

以上就是一个简单的欢迎信息。

以上我们来分析下,调用的"INotificationManager"中的PublishAsync方法。

Paste_Image.png

在源代码的定义中,我们看到了他有8个参数,我们来说说他具体去干嘛了,首先在ABP源代码中调用了这个方法之后,他会到实体NotificationInfo和UserNotification两个实体中进行处理,源代码中的结构很清晰。关联关系很明确是一个一对多的关系。
这个也就是我们在调用PublishAsync方法的时候需要我们键入一个键名,他是全局唯一的,在ABP的代码中的限制也是说明了,禁止使用空格和空字符串。

实时通知

我们刚刚说到了在PublishAsync中,涉及到了UserNotification实体,他的作用是通知用户消息,具体的代码实现中涉及到了后台作业和实时通知SignalR,而我们在客户端获取信息的时候,ABP是触发了一个全局事件。
···
abp.event.on('abp.notifications.received', function (userNotification) {
console.log(userNotification);
});
···
此处涉及的知识点为领域事件中的事件总线。
打印userNotification的Json格式如下:

{
    id: "9c0aaf34-c620-4d05-89df-1f4ae11f3686",
    notification: {
    creationTime: "2017-05-05T01:27:25.7639034Z"
    data: {
    message: "This is a test notification, created at 2017/5/5 1:27:25"
 
    type: "Abp.Notifications.MessageNotificationData"
 }
    entityId: null
    entityType: null
    entityTypeName: null
    id: "724d670e-2cfa-4656-a9b6-ff76ceba5ce3"
    notificationName: "App.SimpleMessage"
    severity: 0
    tenantId: 1
   }
    state: 0
    tenantId: 1
    userId: 2
}

在这个对象中:

  • userId:当前用户Id。通常你不需要知道这个,因为你知道那个是当前用户。

  • state:枚举类型 UserNotificationState 的值。 0:Unread,1:Read。

  • notification:通知详细信息:

  • notificationName: 通知的唯一名字(发布通知时使用相同的值)。

  • data:通知数据。在上面例子中,我们使用了 LocalizableMessageNotificationData (在之前的例子中我们使用它来发布的)。

    • message: 本地化信息。在UI端,我们可以使用 sourceName 和 name 来本地化信息。

    • type:通知数据类型。类型的全名称,包含名称空间。当处理这个通知数据的时候,我们可以检查这个类型。

    • properties:自定义属的基于字典类型的属性。

  • entityType,entityTypeName 和 entityId:实体信息,如果这是一个与实体相关的通知。

  • severity:枚举类型 NotificationSeverity 的值。0: Info, 1: Success, 2: Warn, 3: Error, 4: Fatal。

  • creationTime:表示通知被创建的时间。

  • id:通知的id。

  • id:用户通知id。

以上就是消息通知功能的一个介绍,我们来实现这么个功能吧。

YoYoCms中消息通知的应用

我们继续在NotificationManager中添加方法SendMessageAsync


        public async Task SendMessageAsync(UserIdentifier user, string messager, NotificationSeverity severity = NotificationSeverity.Info)
        {
            await _notificationPublisher.PublishAsync(
                CmsConsts.NotificationConstNames.SendMessageAsync,
                new MessageNotificationData(messager),severity:severity,userIds:new []{user});
        }

然后在Account控制器中进行调用:


        [AbpMvcAuthorize]
        public async Task<ActionResult> TestNotification( string message = "" , NotificationSeverity severity = NotificationSeverity.Info)
        {
            if (message.IsNullOrEmpty())
            {
                message = "这是一条测试消息 " + Clock.Now;
            }
            await _notificationManager.SendMessageAsync(AbpSession.ToUserIdentifier(), message, severity: severity);
          

            return Content("发送提示信息: " + message);
        }

Paste_Image.png
然后我们可以在TenantNotifications和UserNotifications可以看到发布的信息和关联关系。
登陆到管理中心可以看到:

Paste_Image.png

当前的用户信息,通知。

   vm.unReadUserNotificationCount = 0;
            vm.userNotifications = [];
            //格式化消息
            var formattedMessage = function (item) {

                var message = {
                    id: item.id,
                    text: abp.notifications.getFormattedMessageFromUserNotification(item),
                    time: item.notification.creationTime,
                    image: getNotificationImgBySeverity(item.notification.severity),
                    state: abp.notifications.getUserNotificationStateAsString(item.state),
                }

                return message;

            }
            //获取图片路径
            function getNotificationImgBySeverity(severity) {
                switch (severity) {
                    case abp.notifications.severity.SUCCESS:
                        return '/App/assets/yoyocms/notification/1.png';
                    case abp.notifications.severity.WARN:
                        return '/App/assets/yoyocms/notification/2.png';
                    case abp.notifications.severity.ERROR:
                        return '/App/assets/yoyocms/notification/3.png';
                    case abp.notifications.severity.FATAL:
                        return '/App/assets/yoyocms/notification/4.png';
                    case abp.notifications.severity.INFO:
                    default:
                          return '/App/assets/yoyocms/notification/0.png';
                }
            }
            
            //获取所有的消息信息
            vm.getUserNotificationsAsync= function() {
                notificationService.getPagedUserNotificationsAsync({
                    maxResultCount: 5
                }).then(function(result) {
                    vm.unReadUserNotificationCount = result.data.unreadCount;
                    vm.userNotifications = [];
                    $.each(result.data.items,
                        function (index, item) {
                            vm.userNotifications.push(formattedMessage(item));
                        });
                    console.log(vm.userNotifications);
                });

            }
        //标记所有为已读
            vm.makeAllAsRead= function() {
                notificationService.makeAllUserNotificationsAsRead().then(function() {
                    vm.getUserNotificationsAsync();
                });
            }
            //设置消息为已读
            vm.makeNotificationAsRead = function (userNotification) {
                notificationService.makeNotificationAsRead({ id: userNotification.id }).
                    then(function () {
                        for (var i = 0; i < vm.userNotifications.length; i++) {
                            if (vm.userNotifications[i].id == userNotification.id) {
                                vm.userNotifications[i].state = 'READ';
                            }
                        }
                        vm.unReadUserNotificationCount -= 1;

                });
            }


            //初始化方法
            function init() {
                vm.getUserNotificationsAsync();
              
            }

            init();

            //测试为领域事件的一个例子
            abp.event.on('abp.notifications.received', function (userNotification) {
                abp.notifications.showUiNotifyForUserNotification(userNotification);
                vm.getUserNotificationsAsync();
            });
        }

其中有'abp.notifications.received'是一个领域事件的简单实现,大家有兴趣可以继续研究。以上整个功能已经发布到GitHub上,欢迎大家下载使用。

THE END

本开源项目的地址为:https://github.com/ltm0203/YoYoCms
预览网址为:http://www.yoyocms.com/
涉及的技术选型:https://github.com/ltm0203/YoYoCms/tree/dev/doc

转载于:https://www.cnblogs.com/wer-ltm/p/6826476.html

相关文章:

  • bzoj4034: [HAOI2015]树上操作(树链剖分)
  • Leetcode 记录(1~100)
  • ArcGIS Server缓存清理
  • vmware和centos的安装
  • Vue.js中滚动条加载更多数据
  • 如何一键收藏微信文章?
  • 【Linux】【Services】【Project】Haproxy Keepalived Postfix实现邮件网关Cluster
  • 10.2.1 关于vc++不支持把类的成员函数定义为类的友元函数的处理
  • OC 手势可能出现的问题
  • Excel常用12个公式
  • Python web 框架:web.py
  • 【智能家居篇】通信技术简单介绍
  • Linux系统运维之MYSQL数据库集群部署(主主互备)
  • 基于ssh,shell,python,iptables,fabric,supervisor和模板文件的多服务器配置管理...
  • 【bzoj3916】[Baltic2014]friends 字符串hash
  • JavaScript 如何正确处理 Unicode 编码问题!
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • android图片蒙层
  • angular2开源库收集
  • Bootstrap JS插件Alert源码分析
  • express.js的介绍及使用
  • IOS评论框不贴底(ios12新bug)
  • Javascript基础之Array数组API
  • Java编程基础24——递归练习
  • JSONP原理
  • Nacos系列:Nacos的Java SDK使用
  • Netty源码解析1-Buffer
  • php中curl和soap方式请求服务超时问题
  • SQLServer之创建数据库快照
  • 力扣(LeetCode)22
  • 实现菜单下拉伸展折叠效果demo
  • 使用 @font-face
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • [Shell 脚本] 备份网站文件至OSS服务(纯shell脚本无sdk) ...
  • CMake 入门1/5:基于阿里云 ECS搭建体验环境
  • 国内唯一,阿里云入选全球区块链云服务报告,领先AWS、Google ...
  • ​linux启动进程的方式
  • #Ubuntu(修改root信息)
  • #绘制圆心_R语言——绘制一个诚意满满的圆 祝你2021圆圆满满
  • $forceUpdate()函数
  • %3cli%3e连接html页面,html+canvas实现屏幕截取
  • (11)MSP430F5529 定时器B
  • (DFS + 剪枝)【洛谷P1731】 [NOI1999] 生日蛋糕
  • (M)unity2D敌人的创建、人物属性设置,遇敌掉血
  • (二)斐波那契Fabonacci函数
  • (附源码)计算机毕业设计大学生兼职系统
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (三)centos7案例实战—vmware虚拟机硬盘挂载与卸载
  • (一)SpringBoot3---尚硅谷总结
  • (一)VirtualBox安装增强功能
  • (原)记一次CentOS7 磁盘空间大小异常的解决过程
  • (原創) 如何讓IE7按第二次Ctrl + Tab時,回到原來的索引標籤? (Web) (IE) (OS) (Windows)...
  • (转)从零实现3D图像引擎:(8)参数化直线与3D平面函数库