我们是否应该始终为移动后端使用异步JAX-RS资源? [英] Should we always use Asynchronous JAX-RS resources For mobile backend?

查看:74
本文介绍了我们是否应该始终为移动后端使用异步JAX-RS资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java EE-JAX-RS 2.0技术构建移动后端API.

I am building Mobile backend API using Java EE - JAX-RS 2.0 technology.

由于大多数移动客户端使用的都是异步http调用

Since most of mobile client consumes are asynchronous http calls

所以我的问题是: 我应该对所有JAX-RS资源使用异步功能吗?否则原因是什么?

so my question is: Should I use asynchronous feature for all JAX-RS resources? And the reason if not?

下面是模板移动异步API

The below is the template Mobile Async API

@Path("/async_api")
public class AsyncResource {

    @GET
    @Path("/loadUsers")
    @Produces(MediaType.APPLICATION_JSON)
    public void loadUsers(@Suspended AsyncResponse asyncResponse) {

        //TODO: ManagedExecutorService

        new Thread(new Runnable() {

            @Override
            public void run() {
                List users = loadBigUsers();
                asyncResponse.resume(users);
            }

            private List loadBigUsers() {
                return null; // Return big list
            }

        }).start();
    }
}

谢谢!

推荐答案

在JAX-RS中,仅在某些典型情况下才需要@Suspend注释和AsyncResponse.您的代码示例中已经确定了第一种情况.它是长期运行的任务.在这种情况下,AsyncResponse可用于在后台线程中执行长时间运行的代码.乍看之下这没有任何意义,但我们需要考虑应用程序服务器/容器如何处理其请求.通常会有一个线程池来接受和处理客户端请求.如果您在JAX-RS服务方法中内联实现昂贵的操作,则在整个运行时都会阻塞池中的线程之一.使用AsyncResponse,执行程序线程将返回到池中,并且可以并行处理其他请求.

In JAX-RS the @Suspendannotation and AsyncResponse are needed only in certain typical scenarios. The first scenario was already identified in your code example. It is long running tasks. In this case the AsyncResponse can be used to execute long running code in a background thread. While this would not make sense at the first glance we need to think about how an application server / container handles its requests. Usually there is a pool of threads that accepts and handles client requests. If you implement expensive operations inline in your JAX-RS service methods one of the threads in the pool is blocked for the entire runtime. With the AsyncResponse the executor thread gets returned to the pool and other requests can be served in parallel.

@Path("/users")
public class UserRestService {

    @GET
    public void getAllUsers(@Suspend final AsyncResponse asyncResponse) {
        new Thread(new Runnable(
            @Override
            public void run() {
                List<Users> users = UserDAO.loadAllUsers();
                asyncResponse.resume(users);
            }
        ) {}).start();
    }
}

AsyncResponse的第二个应用场景是生产者消费者模式的常见模式.假设您有绑定到URL https://yourservice.at/queue/next的队列,则可以使用@GET方法来阻止take(),比如说LinkedBlockingQueue.在同一URL上,您可以绑定@POST方法,该方法将数据添加到队列中.在这种情况下,您可以将take()操作包装在AsyncResponse中.

The second application scenario for AsyncResponse is the often seen pattern of producer consumer patterns. Assuming you have a queue bound to the URL https://yourservice.at/queue/next then a @GET method can be used for a blocking take() on lets say a LinkedBlockingQueue. On the same URL you could bind a @POST method which adds data to the queue. In this case you would wrap up the functionality with the take() operation in an AsyncResponse.

@Path("/queue/next")
public class MessageQueueService {

    private static final LinkedBlockingQueue<AsyncResponse> suspendedResponses = new LinkedBlockingQueue<AsyncResponse>();

    @GET
    public void getNextMessage(@Suspend final AsyncResponse asyncResponse) {
        MessageQueueService.suspendedResponses.put(asyncResponse);
    }

    @POST
    public void putNewMessage(final String message) throws InterruptedException {
        AsyncResponse asyncResponse = suspendedResponses.take(); // note how this could also block a thread
        asyncResponse.resume(message);
    }
}

从这些说明中,您还可以看到,JAX-RS @Suspended机制用于创建异步服务器端任务.是否在客户端上也以异步方式执行相同的请求完全是另一回事.

From these explanations you can also see, that the JAX-RS @Suspended mechanism is used to create an asynchronous server side task. Whether or not the same request is also executed in an asynchronous manner on the client is a whole different story.

这篇关于我们是否应该始终为移动后端使用异步JAX-RS资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆