本文介绍了Java webapp中请求的异步处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个 Web 应用程序,该应用程序接收大量 HTTP 请求,并且在返回响应之前需要很长时间(30 秒到 2 分钟)来处理每个请求(进而发出其他网络请求).

I need to write a web application which receives a lot of HTTP requests and takes a long time (30s to 2min) to process each request (in turn making other network requests) before returning a response.

因为会有很多请求进来并且这些连接保持打开状态,所以我想沿着事件驱动的路线走,这让我认为 Netty 是合适的.

Because there would be a lot of requests coming in and those connections are held open I'm thinking of going down an event driven route, which leads me to think Netty is appropriate.

如果每个请求都需要很长时间来处理,是否会阻塞netty的处理?或者我可以接收一个请求,然后在将结果返回给请求的连接之前异步处理它吗?

If each request takes a long time to process, is that going to block netty's processing? Or can I receive a request and then asynchronously process it before returning a result to the request's connection?

推荐答案

只要您不阻塞事件循环,您将能够处理大量并发请求(取决于可用内存,以及您为每个请求持有的上下文大小).

As long as you don't block the event loop, you will be able to serve a significant amount of concurrent requests (depending on the available memory, and the size of the context you're holding for each request).

您需要做的是确保以非阻塞方式发出出站网络请求.这通常看起来像这样(在您的 Netty 入站处理程序中):

What you need to do is to make sure you're making the outbound network requests in a non blocking manner. This normally looks like so (in your Netty inbound handler):

CompletableFuture<YourResultType> future = remoteTarget.getStuff();
future.thenApply(ctx::write);

当然,如果您在处理程序之外执行此操作,则需要持有对上下文/通道的引用.

You need to hold a reference to a context / channel if you're doing this outside of the handler of course.

请注意,这是一个简化的答案.如果您发出多个出站请求并有一些业务逻辑,则需要使用期货上的延续或您正在使用的任何非阻塞模型正确拼接您的代码.

Note that this is a simplified answer. If you're making several outbound requests and have some business logic, you need to stitch your code properly using continuations on the futures, or whatever non-blocking model you are using.

这篇关于Java webapp中请求的异步处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 21:05
查看更多