For*_*ick -3 asynchronous http go
我试图以这种方式异步处理Go中的HTTP请求:
我的目标与Java中的Jetty-Continuation非常相似.
如何在GoLang中实现这样的行为?
Grz*_*Żur 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
}
}
Run Code Online (Sandbox Code Playgroud)
和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
}
Run Code Online (Sandbox Code Playgroud)
在Go中,您可以默认获得所需内容.