氛围:单个HttpConnection上的多个订阅

Mar*_*itt 4 java atmosphere

我在我的Spring MVC应用程序中使用Atmosphere来促进推送,使用streaming传输.

在我的应用程序的整个生命周期中,客户端将订阅和取消订阅许多不同的主题.

Atmosphere似乎每个订阅使用一个http连接 - 即每次调用$.atmosphere.subscribe(request)创建一个新连接.这很快耗尽了从浏览器到大气服务器的连接数.

我不想每次都创建一个新资源,而是希望能够AtmosphereResource在初始创建后添加和删​​除广播公司.

但是,由于它AtmosphereResource是入站请求的一对一表示,每次客户端向服务器发送请求时,它都会到达一个新的AtomsphereResource,这意味着我无法引用原始资源,并将其附加到话题的Broadcaster.

我已经尝试过使用它们$.atmosphere.subscribe(request)并调用atmosphereResource.push(request)原始subscribe()调用返回的资源.但是,这没有任何区别.

接近这个的正确方法是什么?

Mar*_*itt 9

以下是我如何使用它:

首先,当客户端进行初始连接时,请确保在调用之前浏览器接受特定于大气的标头suspend():

@RequestMapping("/subscribe")
public ResponseEntity<HttpStatus> connect(AtmosphereResource resource)
{
    resource.getResponse().setHeader("Access-Control-Expose-Headers", ATMOSPHERE_TRACKING_ID + "," + X_CACHE_DATE);
    resource.suspend();
}
Run Code Online (Sandbox Code Playgroud)

然后,当客户端发送其他订阅请求时,尽管它们是不同的resource,但它们包含ATMOPSHERE_TRACKING_ID原始资源.这允许您通过以下方式查找resourceFactory:

@RequestMapping(value="/subscribe", method=RequestMethod.POST)
public ResponseEntity<HttpStatus> addSubscription(AtmosphereResource resource, @RequestParam("topic") String topic)
{
    String atmosphereId = resource.getResponse().getHeader(ATMOSPHERE_TRACKING_ID);
    if (atmosphereId == null || atmosphereId.isEmpty())
    {
        log.error("Cannot add subscription, as the atmosphere tracking ID was not found");
        return new ResponseEntity<HttpStatus>(HttpStatus.BAD_REQUEST);
    }
    AtmosphereResource originalResource = resourceFactory.find(atmosphereId);
    if (originalResource == null)
    {
        log.error("The provided Atmosphere tracking ID is not associated to a known resource");
        return new ResponseEntity<HttpStatus>(HttpStatus.BAD_REQUEST);
    }

    Broadcaster broadcaster = broadcasterFactory.lookup(topic, true);
    broadcaster.addAtmosphereResource(originalResource);
    log.info("Added subscription to {} for atmosphere resource {}",topic, atmosphereId);

    return getOkResponse();
}
Run Code Online (Sandbox Code Playgroud)