折騰了兩天 NATS,踩了不少坑,今天趁機把整個流程整理成一份筆記,重點記錄最讓人頭疼的那個「gnatsd:找不到命令」的錯誤。
先附上官方的自我介紹,方便大家建立初步印象。
NATS
Open Source. Performant. Simple. Scalable.
A central nervous system for modern, reliable
and scalable cloud and distributed systems.

參考 NATS 官網的說明。
NATS Server
NATS provides a server that is written in the Go programming language. The executable name for the NATS server is gnatsd, which stands for Go NATS Deamon. The NATS server is provided as open source software under the MIT license. Apcera actively maintains and supports the NATS server.
從官方介紹不難看出,NATS 是用 Go 語言編寫的,所以要跑起 NATS,前提是先把 Go 環境準備好。
Install and Run NATS Server
In this tutorial you install and run the NATS server (gnatsd). You can follow this same procedure anytime you want to run the NATS server.
Prerequisite
Set up your Go environment
下載頁面:
https://golang.org/dl/
依照自己電腦的架構挑選對應的安裝包。

進入安裝包所在的目錄,這裡以「下載」資料夾為例。
cd 下載

接著把壓縮包解開到 /usr/local 目錄。
tar -zxvf go1.6.linux-amd64.tar.gz -C /usr/local
先貼出我的 /etc/profile 配置。

由於我的環境變數裡同時還有 Java 與 Maven,所以看起來比較雜亂,讀者只要關注 Go 的部分即可。
Go 的環境變數主要有三個:GOPATH、GOROOT,以及 PATH。
On Mac OS X and Linux, by default Go is installed to directory /usr/local/go/, and the GOROOT environment variable is set to /usr/local/go/bin
Your Go working directory (GOPATH) is where you store your Go code. It can be any path you choose but must be separate from your Go installation directory (GOROOT).
簡單說,GOROOT 是 Go 的安裝路徑,GOPATH 則是存放程式碼的工作目錄。
把 GOROOT 指向剛才解壓的位置,也就是 /usr/local/go。
GOROOT=/usr/local/go
在當前使用者目錄下建立一個資料夾。
cd ~
mkdir go
把它作為 GOPATH,也就是程式碼的存放目錄。
GOPATH=$HOME/go
配置 PATH,把 $GOROOT/bin 與 $GOPATH/bin 都加進去。這裡特別提醒:一定要把 $GOPATH/bin 也放進 PATH,原因後面會說明。
至此,環境變數就配置完成了。
在當前使用者目錄下建一個 goworkspace 資料夾來放程式碼。
寫一個最經典的 Hello World。
mkdir goworkspace
cd goworkspace
touch hello.go
vi hello.go
把下面的內容貼進 hello.go 並存檔。
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
然後執行看看。
go run hello.go

https://nats.io/documentation/tutorials/go-install/
https://golang.org/doc/install
在終端執行以下指令。
go get github.com/nats-io/gnatsd
這條指令會把 gnatsd 服務安裝到剛才配置的 GOPATH 中。執行前請確保電腦上已經裝好並配置了 git。
git 的安裝可參考相關教學(例如 Ubuntu 安裝 git 的說明)。
指令執行完畢後,$HOME/go 目錄下會多出一些內容。

而 gnatsd 就位於其中的 bin 目錄裡。
我們進入 /usr/local/go/bin 查看。

可以發現裡面只有 go、godoc 和 gofmt 三個檔案。
為了能在終端直接執行 gnatsd 指令,我們必須把 $GOPATH/bin 加入 PATH。如果 PATH 裡沒有 $GOPATH/bin,執行:
gnatsd
就會看到這樣的提示。
gnatsd:找不到命令

只要把 $GOPATH/bin 正確配置進 PATH,就能成功啟動 gnatsd 服務了。

https://nats.io/documentation/tutorials/gnatsd-install/