近日Nginx官方發佈了nginx unit的1.0版本,做爲靠Nginx混飯吃的一員,免不了先體驗一把。php
unit是一個動態的web應用服務器,採用了相似php-fpm的機制,不過支持Python/Go/Perl/Ruby/PHP等多種語言,後面也會增長對Java/Javascript的支持。linux
clone源碼倉庫nginx
$ git clone https://github.com/nginx/nginx.git
進入目錄執行configuregit
$ ./configure
這裏配置對go的支持,其餘的語言配置相似,可參考官方文檔github
首先要安裝golang環境,能夠在這裏下載相應的二進制包安裝。安裝過的能夠跳過。golang
$ wget https://dl.google.com/go/go1.10.1.linux-amd64.tar.gz $ tar -xf go1.10.1.linux-amd64.tar.gz -C /usr/local/ $ export PATH=$PATH:/usr/local/go/bin
在用戶的目錄下新建文件夾go
做爲go的工做目錄,並設置環境變量GOPATHweb
$ mkdir $HOME/go $ export GOPATH=$HOME/go
配置unit對golang的支持,主要工做是爲go引入了 "nginx/unit"包,用於在go中調用json
$ ./configure go $ make go-install
$ cd $GOPATH $ mkdir src/unit-demo $ vim ./src/unit-demo/main.go
main.go中的代碼以下vim
package main import ( "fmt" "net/http" "nginx/unit" ) func handler(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "text/plain"); fmt.Fprintf(w, "Method : %s\n", r.Method) fmt.Fprintf(w, "URL : %s\n", r.URL.Path) fmt.Fprintf(w, "Host : %s\n", r.Host) } func main() { http.HandleFunc("/", handler) unit.ListenAndServe("8000", nil) }
這裏和普通的go實現的http服務器最大的區別是調用unit.ListenAndServe而不是http.ListenAndServe。編譯後的程序在做爲單獨的程序使用時,unit.ListenAndServe和http.ListenAndServe徹底相同。經過unit啓動時,uint.ListenAndServe的參數被忽略,真正的監聽端口經過環境變量從unit的主程序中獲取,而不是使用參數裏的8000端口。這裏也能夠不用"8000"而用其餘的端口。後端
編譯安裝go程序
$ go install unit-demo
$ cd /path/to/unit $ make $ ./build/unitd
unit貌似配置項不多,並且只能經過unix socket配置 這裏爲了簡單用curl來配置
新建一個unit.config的文本文件,輸入下面的配置
{ "applications": { "example_go": { "type": "go", "executable": "/home/kenan/go/bin/unit-demo" } }, "listeners": { "*:8500": { "application": "example_go" } } }
配置裏listeners表示監聽地址及對應的處理程序,applications對應全部的處理程序的信息,type
爲go表示是golang程序,executable
爲可執行文件路徑。對於8500端口的HTTP請求,將有前面生成的unit-demo程序處理
經過curl將unit.config文件內容傳遞給unitd程序,返回Reconfiguration done
表示配置成功。
$ curl -X PUT -d @unit.config --unix-socket control.unit.sock http://localhost/ { "success": "Reconfiguration done." }
用curl訪問,能夠看到返回的結果。
$ curl http://localhost:8500/t Method : GET URL : /t Host : localhost:8500
比起Nginx,unit更像是一個進程管理器。以往對於多個後端的應用程序須要分別管理,現在unit一個程序就能夠實現。若是一個項目使用了PHP/Python/Go/Ruby等多種語言,用unit來管理一切貌似也是不錯的選擇。