设计可扩展 Web 服务的模式
我正在用 Java 编写一个 Web 服务,它需要每秒处理大量请求。一般流程为:
- Web 服务接收来自客户端的请求
- 将“继续轮询我”响应返回给客户端
- 调用另一个 Web 服务(或 服务),并等待他们 响应(超时)
- 客户端轮询我们的网络服务,直到 它收到一个响应(带有 通过
在 Internet 上进行研究,我发现了两种编写 Web 服务的通用方法:
- 为每个请求生成一个线程
- 使用 Reactor 模式(中央调度程序线程响应 IO 事件)
您是否建议哪种方法通常更好?每种方法的优点/缺点是什么?我也希望能提供一些例子。
I am writing a web service in Java which needs to handle a large number of requests / second. The general flow will be:
- Web service receives a request from client
- Returns a 'keep polling me' response to client
- Calls another web service (or
services), and waits for them to
respond (with a timeout) - Client polls our web service, until
it receives a response (with a
timeout)
Researching on the Internet, I have found two general approaches to writing web services:
- Spawn a thread for each request
- Use the Reactor pattern (central dispatcher thread responds to IO events)
Do you have a recommendation for which approach is generally better, and what are the pros/cons of each approach? I would also appreciate pointers to examples.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要考虑多线程。异步思考。我碰巧刚刚编写了一个异步处理程序,该处理程序在 IIS 中以 <10 个线程运行 2,000 RPS。不确定 java 是如何工作的,因为我是 .net 人员,但我相信他们有类似的 BeginXXX/EndXXX 方法。如果您曾经生成一个线程,那么您就不会考虑您的代码可能阻塞的所有位置:数据库 IO、文件 I/O、Web 服务等。这些是您的性能会导致站点变慢的地方。
异步,异步,异步。
念诵并重复。
Don't think multi-threading. Think asynchronously. I happened to have just coded an async handler that ran 2,000 RPS with <10 threads in IIS. Not sure how java works since I'm a .net guy but I gotta believe they have similar BeginXXX/EndXXX methods. If you ever spawn a thread then you're not considering all the places your code can block: data base IO, File I/O, web services, etc. These are the places your performance will cause your site to be slow.
Async, Async, Async.
Chant and repeat.
除了“不退款不退货”响应之外,我想说的是“异步思考”,因为您应该允许容器管理其已部署的 Web 服务的多线程/可扩展性和高可用性问题,这允许您可以使用应用程序容器来设置集群等内容。
编辑:所以总之,不存在这样的模式,也许您应该探索应用程序容器的可扩展性/可用性功能......
In addition to "No Refunds No Returns" response, I'd say yeah "Think Asynchronously" as you should be allowing your container to manage the multi-threading/scalability and high-availability issues of the web services it has deployed, this allows you to set-up things like clustering and so forth using your application container.
EDIT: So in conclusion, there isn't a pattern as such, maybe you should explore the scalability/availability features of your application container...
异步确实是正确的方法,但不要自己管理它,请使用支持异步 Web 服务调用的东西,例如 JAX-WS 2.0(它使用
Future
接口和/或Executor
来自java.util.concurrent
的 code> 框架)。请参阅 异步 Web 服务使用 JAX-WS 2.0 进行调用。Asynchronism is indeed the right approach but don't manage this yourself, use something that supports asynchronous web service invocation like JAX-WS 2.0 (which uses the
Future
interface and/or theExecutor
framework fromjava.util.concurrent
). See Asynchronous Web Service Invocation with JAX-WS 2.0.