异步http请求处理

时间:2018-03-13 11:15:59

标签: http asynchronous go

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

  1. 我将处理程序函数传递给HTTP服务器
  2. 在处理程序中,我将HttpRequest / HttpResponse对象存储在切片或地图中
  3. 从处理程序函数返回时 - 响应未返回给客户端,但连接仍保持打开状态
  4. 当从另一个源收到“some”异步输入时,我从内存中获取相关的HttpRequest / HttpResponse对象,编写响应并关闭连接。
  5. 我的目标非常类似于Java中的Jetty-Continuation。

    如何在GoLang中实现这样的行为?

1 个答案:

答案 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中,您可以默认获得所需内容。

相关问题