16

我想用气氛来开发一个通知系统。

我对 Atmosphere 很陌生,如果我在某个地方错了,我深表歉意。我所理解的是,当演员发布某些内容时,我会将通知操作保存到数据库中。我不明白接收者将如何实时接收这些通知。

我认识的发件人会执行以下操作

event.getBroadcaster().broadcast(
            objectMapper.writeValueAsString("Some Message"));

现在我无法弄清楚接收者如何接收此消息。

例如 。我想添加一个用户对象作为朋友。因此,当用户 1 添加用户 2 用户 1 广播时,而不是我如何将通知推送给用户 2。我很难理解这一点。

从技术上讲,我想要类似 facebook 或 gmail 通知的东西,在用户活动中其他用户会收到通知。

4

1 回答 1

26

基本上你需要的是在 Atmosphere 之上实现Publish-subscribe 。

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

首先你需要配置服务器端:安装大气

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

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

Broadcaster其实就是这些资源的一个容器,这样在需要发送到多个连接的时候就不需要去处理lookup/iteration/concurrency了。(请注意,单个客户端可以产生多个连接)。

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

@RequestMapping(value = "/user-notifications/{userId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public 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. 服务器接收请求,暂停并在某处(在您的代码或广播器中)保存连接。
  3. 当发生某些事情时,服务器会查找挂起的连接并在其中发送通知。
  4. 客户端收到通知并调用回调。
  5. 利润!!!

该 wiki对 Atmosphere 背后的一些概念进行了解释,并提供了指向其他文档的链接。

于 2013-11-21T14:23:05.323 回答