注册服务
可以通过提供服务定义文件和调用HTTP API这两种方式来注册一个服务。
提供服务定义文件
- 首先,为consul配置创建一个目录,consul会载入配置文件夹里的所有配置文件。在Unix系统中通常类似/etc/consul.d(.d后缀的意思是这个路径包含了一组配置文件)。如果在创建集群时为在命令行中创建,则需要手动创建(
mkdir /etc/consul.d
)。 - 随后在
/etc/consul.d
目录下创建web.json
。
// web.json
{
"service": {
"name": "web",
"tags": ["master"],
"address": "127.0.0.1",
"port": 10000,
"checks": [
{
"http": "http://localhost:10000/health",
"interval": "10s"
}
]
}
}
- 在GOPATH或者go mod路径下创建并运行一个监听HTTP:10000的health服务。参考文件
hello.go
。
// hello.go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Hello Web3! This is n3 or n2")
fmt.Fprintf(w, "Hello Web3! This is n3 or n2")
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("health check! n3 or n2")
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/health", healthHandler)
http.ListenAndServe(":10000", nil)
}
- 结果:对应运行的系统中会每隔10s输出
health check! n3 or n2
。原因是web.json文件中定义了checks的interval属性
。会每隔十秒到服务中访问。 - 上面注册的Web服务,它的域名是
web.service.consul
。
// 可以通过以下命令接收包含地址和端口的SRV记录,也可以使用DNS API来接收
dig @127.0.0.1 -p 8600 web.service.consul