基本上你需要的是在 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);
所以,总结一下:
- 客户发送请求“我想收到这种通知”。
- 服务器接收请求,暂停并在某处(在您的代码或广播器中)保存连接。
- 当发生某些事情时,服务器会查找挂起的连接并在其中发送通知。
- 客户端收到通知并调用回调。
- 利润!!!
该 wiki对 Atmosphere 背后的一些概念进行了解释,并提供了指向其他文档的链接。