我正试图以这种方式异步处理Go中的HTTP请求:
我的目标非常类似于Java中的Jetty-Continuation。
如何在GoLang中实现这样的行为?
答案 0 :(得分:10)
在Go中你不需要这种行为。
Java HTTP服务器使用线程,如果servlet等待某些东西,它会有效地阻塞当前线程。线程很重,线程池有限。
在Go中,HTTP服务器实现使用goroutines,如果它们正在等待,它们将不会阻止操作系统线程。 Goroutines是轻量级的,并由Go运行时有效地安排。通过有效调度,我的意思是当goroutine进行系统调用或等待通道时进行切换。
简单来说,不要尝试从Java servlet复制变通方法,因为Go中不需要变通方法。
让我们考虑一个Java servlet,servlet共享操作系统线程
class Slow extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
Thread.sleep(1000);
// stops the thread for a second
// operating system puts a thread aside and reuses processor
// it is out of Java control
// when all pooled HTTP server threads are sleeping no request is served
}
}
和Go HTTP处理程序,每个处理程序都在一个单独的goroutine
中运行func fast(w http.ResponseWriter, r *http.Request) {
time.Sleep(10000 * time.Second)
// Go scheduler puts the goroutine aside
// and reuses OS thread for handling another request
// when one second passes the goroutine is scheduled again
// and finishes serving request
}
在Go中,您可以默认获得所需内容。