异步http请求处理

For*_*ick -3 asynchronous http go

我试图以这种方式异步处理Go中的HTTP请求:

  1. 我将处理函数传递给HTTP服务器
  2. 在处理程序中,我将HttpRequest/HttpResponse对象存储在切片或地图中
  3. 从处理程序函数返回时 - 响应不会返回给客户端,但连接仍保持打开状态
  4. 当从另一个源接收"some"异步输入时,我从内存中获取相关的HttpRequest/HttpResponse对象,写入响应并关闭连接.

我的目标与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中,您可以默认获得所需内容.