程序化Jersey AsyncResponse处理

时间:2019-03-04 10:46:34

标签: asynchronous jersey rest-assured

我正在使用程序化api(例如Inflector等)在Jersey上工作,我的要求是添加超时处理,以防在每种情况下未在配置的时间内返回响应。因此,我进行了同步通话,但如下所示使其异步:

    @Inject
private javax.inject.Provider<AsyncResponse> responseProvider;

/**
 * 
 */
@Override
public Response apply(final ContainerRequestContext context) {
    final AsyncResponse asyncResponse = responseProvider.get();
    asyncResponse.setTimeoutHandler(new TimeoutHandler() {

        @Override
        public void handleTimeout(AsyncResponse asyncResponse) {
            AbstractPaymentEndpointHandler.this.handleTimeout(asyncResponse);
        }
    });
    enrichContext(context, asyncResponse);
    ThreadFactory threadFactory = ThreadFactoryProvider.getProvider().getThreadFactory("default");
    ExecutorService service = Executors.newSingleThreadExecutor(threadFactory);
    service.submit(new Runnable() {
        @Override
        public void run() {
            Response resp = null;
            try {
                resp = applyInternal(context);
            } catch (StillProcessingException spex) {
                asyncResponse.cancel();
                createStillProcessingResponse();
            }
            if (resp != null) {
                asyncResponse.resume(resp);
            }
        }
    });
    return null;//remember asyncResponse.resume will return the response of this call
}

任何扩展此Inflector的处理程序都将使其在指定的超时下异步处理任何调用(enrichContext设置超时值)。发生超时后,我应该执行以下操作:

  1. 如果方案配置为超时后继续,我会向Http 100发送自定义消息“仍在处理中”,然后将其保留。

  2. 如果方案配置为超时后中止,我将发送带有消息“ Abort Requested”的Http 503并保留给它。

我的handleTimeout回调实现是这样的:

@Override
protected void handleTimeout(AsyncResponse asyncResponse) {
    //if scenario is continue createStillProcessingResponse
     asyncResponse.resume(createStillProcessingResponse());
    //if scenario is abort createAbortResponse 
     asyncResponse.resume(createAbortResponse());
}


protected Response createStillProcessingResponse() {
    //build 'still processing' type of response
    TimeoutResponseMessage message = new TimeoutResponseMessage();
    message.setHttpStatus(100);
    message.setCode("CONT");
    message.setMessage("Still processing");
    return Response.status(message.getHttpStatus()).type(MediaType.APPLICATION_JSON).entity(message).build();
}

当我需要继续(HTTP 100)带有上述消息的HTTP代码时,这总是发送200个响应,没有ResponseBody。
其次,通过校准asyncResponse.resume发送响应是否正确? 另外,如果我在超时后致电取消,会发生什么。我的处理会被取消还是继续?因为当我打电话取消服务器时,将Http 503服务发送回给我。
在程序化异步处理方面是否有一些好的帮助,因为我感觉缺少一些东西来使我的解决方案更可靠。

0 个答案:

没有答案