如何使用Atmosphere设计推送通知

Sau*_*mar 14 java spring spring-mvc atmosphere

我想用气氛来开发通知系统.

我是Atmosphere的新手,如果我在某个地方错了,请道歉.我理解的是当Actor发布我将通知操作保存到数据库的东西时.我不明白接收器如何实时接收这些通知.

我知道的发件人会做以下事情

event.getBroadcaster().broadcast(
            objectMapper.writeValueAsString("Some Message"));
Run Code Online (Sandbox Code Playgroud)

现在我无法弄清楚接收器如何接收此消息.

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

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

elu*_*ode 22

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

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

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

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

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

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

在服务器端,您需要为客户端提供端点以订阅通知.例如,如果您使用的是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);
}
Run Code Online (Sandbox Code Playgroud)

当事情发生时你可以通知这样的客户:

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

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

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);
Run Code Online (Sandbox Code Playgroud)

所以,总结一下:

  1. 客户端发送请求"我想收到此类通知".
  2. 服务器接收请求,暂停并保存连接(在您的代码或Broadcaster中).
  3. 当发生某些事情时,服务器会查找挂起的连接并在其中发送通知
  4. 客户端接收通知并调用回调.
  5. 利润!!!

这个wiki解释了Atmosphere背后的一些概念以及其他文档的链接.