`

Send response and then process - async processing

阅读更多
If your request processing takes long time to run, client might be timed out before processing completed. One solution is to send back the response (method returns) and then process the request in a different thread.

/*
* This is the normal sync processing. Client might be timed out if 
* processing takes a while to finish and then the method returns.
*/
    @POST
    @Path("/test")
    public void test() {
        System.out.println("==== Normal test started");

        try {
            System.out.println("==== Normal task started: " + Instant.now());
            Thread.sleep(15000);
            System.out.println("==== Normal task finished: " + Instant.now());
        } catch (InterruptedException ie) {}

        System.out.println("==== Normal test completed");
    }

## console output: everything happens in order. If it took longer than 15 seconds, client could be timed out:
==== Normal test started
==== Normal task started: 2017-10-12T01:25:10.054Z
==== Normal task finished: 2017-10-12T01:25:25.055Z
==== Normal test completed


/* Async processing. The method would return immediately after the request received.
* processing(task) would happen afterwards, so that client would not be timed out.
*/
    @POST
    @Path("/testAsync")
    public Response testAsync() {
        System.out.println(">>>> Async test started");

        Runnable task = () -> {
            try {
                System.out.println(">>>> async task started: " + Instant.now());
                //Thread.sleep(15000);
                TimeUnit.SECONDS.sleep(15);
                System.out.println(">>>> async task finished: " + Instant.now());
            } catch (InterruptedException ie) {}
        };

        Executors.newSingleThreadExecutor().execute(task);

        System.out.println(">>>> Async test completed");
        return Response.status(OK).entity("service completed!").build();
    }

## console output: method returns immediately and then task starts in a different thread:
>>>> Async test started
>>>> Async test completed
>>>> async task started: 2017-10-12T01:25:33.673Z
>>>> async task finished: 2017-10-12T01:25:48.675Z



/**
* The following is jax-rs 2.0 AsyncResponse.
*/
    @POST
    @Path("/asyncResponse")
    public void testAsyncResponse(@Suspended AsyncResponse asyncResponse) {
        System.out.println("## testAsyncResponse started");

        new Thread() {
            public void run() {
                try {
                    System.out.println("## testAsyncResponse task started: " + Instant.now());
                    Thread.sleep(15000);
                    System.out.println("## testAsyncResponse task finished: " + Instant.now());
                } catch (InterruptedException ie) {}

                // Send processing result: if suspended AsyncResponse is not resumed or cancelled, client would be timed out
                Response response = Response.ok().entity("Processed Successfully").build();
                asyncResponse.resume(response);
            }
        }.start();

        System.out.println("## testAsyncResponse completed");
    }
分享到:
评论

相关推荐

    android-async-http-1.4.9下载

    在Android应用开发中,网络通信是必不可少的一部分,而`android-async-http`库是一个非常流行的异步HTTP客户端库,特别适合处理与服务器的交互。这个库由Leonardo Uribe创建,它提供了简单易用的API,使开发者可以...

    mongodb-async-driver-2.0.1 jar包

    MongoDB异步驱动程序(mongodb-async-driver)是为Java开发者设计的一个库,它允许应用程序以非阻塞的方式与MongoDB服务器进行通信,提高了处理大量并发请求的能力。 在"mongodb-async-driver-2.0.1.jar"这个特定...

    android-async-http的jar包

    Android-Async-Http是一个流行的开源库,用于在Android应用程序中执行异步HTTP请求。这个库由Loopj开发,简化了网络交互的过程,使得开发者能够更高效地处理网络操作,而无需阻塞主线程,从而避免ANR(Application ...

    前端开源库-babel-helper-remap-koa2-async-to-generator

    前端开源库-babel-helper-remap-koa2-async-to-generatorbabel-helper-remap-koa2-async-to-generator,将异步函数转换为ES2015生成器(koav2->koav1)。

    android-async-http 源码

    Build Status ...https://github.com/loopj/android-async-http/blob/1.4.9/CHANGELOG.md Javadoc Latest Javadoc for 1.4.9 release are available here (also included in Maven repository): ...

    前端开源库-babel-plugin-transform-async-to-promises

    3. **转换过程**:`babel-plugin-transform-async-to-promises`工作原理是,首先识别出`async function`和`await`关键字,然后将它们替换为基于Promise的操作,如`.then()`和`.catch()`。这样,即使目标环境不支持`...

    mongodb-async-driver-2.0.1驱动.zip

    mongodb-async-driver-2.0.1驱动文件 jar MongoDB Async Java Driver Documentation Welcome to the MongoDB Async Java driver documentation hub. Getting Started The Getting Started guide contains ...

    Android android-async-http-1.4.9

    `android-async-http-1.4.9` 是一个专为Android设计的异步HTTP库,它简化了网络请求的处理流程,使开发者能够更高效地进行网络通信。这个库由Leonard Brünings创建,并且在早期的Android开发中广泛使用。 ### 异步...

    vue-async-computed, Vue.js的异步计算属性.zip

    vue-async-computed, Vue.js的异步计算属性 vue-async-computed 这里插件的为Vue兼容 ! 可以使用这个插件在Vue中计算出异步计算的属性。不使用这里插件,你无法执行这里操作:new Vue({ data: { us

    node-child-process-async:覆盖Node的child_process模块​​的最佳方法w Promises

    我们还是回到一个ChildProcess的实例,只需用.then()和.catch()添加到它,使其答应友好。 安装 npm install --save child-process-async 用法 // OLD: const { exec , spawn } = require ( 'child_process' ) ; // ...

    android-async-http-master

    "Android-Async-Http"是一个流行的开源框架,专为Android平台设计,用于简化网络请求处理。这个框架的主要目标是让Android开发者能够更高效、更轻松地进行异步HTTP通信,从而获取网络数据或向服务器发送数据。在...

    android-async-http官方项目

    android-async-http官方项目:来自Github; 该项目中包含了多个版本的android-async-http.jar包,目前最新版本是:android-async-http-1.4.5.jar; 地址:原项目地址:https://github.com/loopj/android-async-http

    android-async-http-1.4.11.zip

    1)包里包含android-async-http-1.4.11.jar 和 httpclient-4.5.8.jar两个文件 2)强大的网络请求库,主要特征如下: 处理异步Http请求,并通过匿名内部类处理回调结果 Http请求均位于非UI线程,不会阻塞UI操作 通过...

    前端开源库-fis-postprocessor-require-async

    `fis-postprocessor-require-async`库则是针对`require.async`进行后处理的工具,它能够分析并记录`require.async`加载的组件,使得构建过程更加智能化和可控。 首先,我们需要理解`require.async`的工作原理。在...

    android-async-http-1.4.8.jar

    强大的网络请求库,主要特征如下: 处理异步Http请求,并通过匿名内部类处理回调结果 Http请求均位于非UI线程,...通过线程池处理并发请求 处理文件上传、下载 响应结果自动打包JSON格式 自动处理连接断开时请求重连

    android-async-http-1.4.5.jar

    最新异步网络请求android-async-http-1.4.5.jar

    android-async-http-1.4.3最新jar包

    android的异步网络加载,方便使用,免去多余的代码

    前端开源库-multihashing-async

    **前端开源库 `multihashing-async` 深度解析** 在当今的Web开发领域,前端开源库扮演着至关重要的角色,它们为开发者提供了强大的工具和功能,以提高开发效率和代码质量。`multihashing-async` 就是这样一个专为...

    android-async-http

    android-async-http开源框架可以是我们轻松的获取网络数据或者向服务器发送数据,使用起来也很简单,具体详细使用看官网:https://github.com/loopj/android-async-http

    android-async-http-master.zip

    《Android异步HTTP框架——深入理解android-async-http-master》 在移动开发领域,尤其是在Android平台上,网络请求是不可或缺的一部分。高效、稳定的网络通信库能够极大地提升应用的用户体验。"android-async-...

Global site tag (gtag.js) - Google Analytics