在 Google App Engine (GAE) 上,前端实例可以创建多达 10 个线程以最大化吞吐量。根据this page ,这样的多线程可以实现如下:
Runnable myTask = new Runnable({
@Override
public void run() {
// Do whatever
}
});
ThreadFactory threadFactory = ThreadManager.currentRequestThreadFactory();
// GAE caps frontend instances to 10 worker threads per instance.
threadFactory.newRequestThread(myTask);
为了访问我的 GAE 服务器端,我将公开许多映射到特定 URL 的 servlet,例如映射到 http://myapp.com/fizz
的 FizzServlet
>:
public class FizzServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Handle the request here. Somehow send it to an available
// worker thread.
}
}
我想我对如何将这两个想法联系起来感到窒息。据我所知,这里有 3 种不同的机制/项目:
- App Engine 实例本身,我可以通过实现
ServletContextListener
来“ Hook ”它的生命周期,并在 GAE 启动实例时运行自定义代码;和 - 这个
ThreadFactory
/ThreadManager
东西(上面) - servlets/监听器
我想我想知道如何实现代码,以便每次收到新请求时,比如 FizzServlet#doGet
,如何确保将请求发送到可用线程(如果有一个可用)。这样,如果 FizzServlet
是我公开的唯一 servlet,它可能会被调用多达 10 次,然后才会导致新的(第 11 个)传入请求在处理前一个请求时挂起。
我正在寻找 servlet 和线程创建代码之间的粘合代码。提前致谢。
最佳答案
I guess I'm wondering how to implement code such that every time a new request comes into, say, FizzServlet#doGet, how to make sure that request gets sent to an available thread (if there is one available). That way, if FizzServlet was the only servlet I was exposing, it could get called up to 10 times before it would cause a new (11th) incoming request to hang while a previous request was processing.
这就是 GAE servlet 引擎为您所做的。您部署一个包含 servlet 的应用程序,当请求进来时,servlet 引擎使用一个线程来处理请求并调用您的 servlet。你无事可做。
如果您的 servlet 的 doGet()
或 doPost()
方法由 GAE 调用,需要并行执行多项任务(例如联系其他几个网站) ,然后您将按照您链接到的页面中的说明自行启动线程。
关于java - 多线程和 Google App Engine Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676353/