栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Atmosphere设计推送通知

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Atmosphere设计推送通知

基本上,您需要在Atmosphere之上实现发布-
订阅

气氛由两部分组成:客户端(基于javascript)和服务器端(基于java)。

首先,您需要配置服务器端:安装Atmosphere

这是servlet或过滤器,它是必需的,以便可以将AtmosphereResource添加到 HttpServletRequest中

AtmosphereResource表示服务器端的单个客户端连接。

Broadcaster 实际上是这些资源的容器,因此当您需要发送到多个连接时,您不需要处理查找/迭代/并发。(请注意,单个客户端可以产生多个连接)。

在服务器端,您需要为客户端提供一个端点来订阅通知。例如,如果您使用的是Spring-MVC,它可能会像这样(省略验证/身份验证等):

@RequestMapping(value = "/user-notifications/{userId}")@ResponseStatus(HttpStatus.OK)@ResponseBodypublic void watch(@PathVariable("userId") String userId,       HttpServletRequest request) throws Exception {    //Atmosphere framework puts filter/servlet that adds ATMOSPHERE_RESOURCE to all requests    AtmosphereResource resource = (AtmosphereResource)request.getAttribute(ApplicationConfig.ATMOSPHERE_RESOURCE);    //suspending resource to keep connection    resource.suspend();    //find broadcaster, second parameter says to create broadcaster if it doesn't exist    Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(userId,true);    //saving resource for notifications    broadcaster.addAtmosphereResource(resource);}

发生某些情况时,您可以像这样通知客户:

public void notify(User user, Event event){    Broadcaster b = BroadcasterFactory.getDefault().lookup(user.getId());    if (b!=null){        b.broadcast(event);    }}

在客户端,您需要发送订阅请求并侦听后续事件,如下所示:

var request = new atmosphere.AtmosphereRequest();request.url = '/user-notifications/'+userId;request.transport = 'websocket';request.fallbackTransport = 'streaming';request.contentType = 'application/json';request.reconnectInterval = 60000;request.maxReconnectOnClose = 1000;request.onMessage = function(response){    console.log(response);    alert('something happend<br>'+response);};that.watcherSocket = atmosphere.subscribe(request);

因此,总结一下:

  1. 客户端发送请求“我想接收这种通知”。
  2. 服务器接收请求,挂起并将连接保存在某个地方(在您的代码中或在Broadcaster中)。
  3. 当发生某种情况时,服务器会查找暂停的连接并在其中发送通知。
  4. 客户端收到通知并调用回调。
  5. 利润!!!

该Wiki解释了Atmosphere背后的一些概念,并提供了其他文档的链接。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号