在Go web伺服器中實現prefork和affinity

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Apache伺服器可是使用prefork技術,啟動多個獨立的進程,每個進程獨立的處理http請求,不需要擔心安全執行緒的問題。

This Multi-Processing Module (MPM) implements a non-threaded, pre-forking web server that handles requests in a manner similar to Apache 1.3. It is appropriate for sites that need to avoid threading for compatibility with non-thread-safe libraries. It is also the best MPM for isolating each request, so that a problem with a single request will not affect any other.

儘管prefork在處理高並發的情況下並不高效,但是作為一個技術,倒是有啟發我們的地方。我最近在調研Go伺服器的效能看到一段代碼,很優雅的實現了prefork和affinity的的功能,特地抄寫在本文中,看看他是怎麼實現的。

代碼出處: WebFrameworkBenchmark go-fasthttp。

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
package mainimport ("flag""fmt""io""log""net""os""os/exec""runtime""github.com/valyala/fasthttp""github.com/valyala/fasthttp/reuseport")var (addr     = flag.String("addr", ":8080", "TCP address to listen to")prefork  = flag.Bool("prefork", false, "use prefork")affinity = flag.Bool("affinity", false, "use affinity for prefork")child    = flag.Bool("child", false, "is child proc"))func main() {flag.Parse()ln := getListener()if err := fasthttp.Serve(ln, requestHandler); err != nil {log.Fatalf("Error in ListenAndServe: %s", err)}}func requestHandler(ctx *fasthttp.RequestCtx) {io.WriteString(ctx, "Hello World")}func getListener() net.Listener {if !*prefork {ln, err := net.Listen("tcp4", *addr)if err != nil {log.Fatal(err)}return ln}if !*child {children := make([]*exec.Cmd, runtime.NumCPU())for i := range children {if !*affinity {children[i] = exec.Command(os.Args[0], "-prefork", "-child")} else {children[i] = exec.Command("taskset", "-c", fmt.Sprintf("%d", i), os.Args[0], "-prefork", "-child")}children[i].Stdout = os.Stdoutchildren[i].Stderr = os.Stderrif err := children[i].Start(); err != nil {log.Fatal(err)}}for _, ch := range children {if err := ch.Wait(); err != nil {log.Print(err)}}os.Exit(0)panic("unreachable")}runtime.GOMAXPROCS(1)ln, err := reuseport.Listen("tcp4", *addr)if err != nil {log.Fatal(err)}return ln}

這個程式使用fast-http簡單的實現了一個web伺服器,簡單的返回一個hello world

如果程式啟動的時候加上了-prefork參數,它會使用exec.Command啟動多個子進程,子進程的數量和CPU的核心數相同(第51行)。

如果程式啟動的時候加上了-prefork參數和"-affinity"參數,它會將子進程綁定在其中的一個CPU核上,這樣這個子進程只會被這個CPU執行。

子進程限定了使用的原生線程為1: runtime.GOMAXPROCS(1)

因為程式使用了reuseport,所以不會導致多個IP地址和連接埠被佔用的情況,多個子進程可以共用相同的IP地址+連接埠監聽。

需要注意的事,reuseport並不是所有的作業系統都支援,比如目前windows就不支援,所以只可能在高版本的Linux中使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.