近日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来管理一切貌似也是不错的选择。