fabio是一个给consul上的服务调用提供一个负载均衡的能力(不在需要自己基于consul watch 来实现一个负载均衡了)
本文简单记录了搭建的过程
一 准备
1 下载 fabio
github.com/fabiolb/fabio
go install
2下载 consul
github.com/hashicorp/consul
go install
二 运行
1 启动consul
consul agent -dev
2 启动fabio
fabio
3 demo
package main
import (
"fmt"
"net/http"
"time"
"github.com/hashicorp/consul/api"
)
const (
port = 5003
name = "testfabio"
)
func main() {
consulCfg := api.DefaultConfig()
client, err := api.NewClient(consulCfg)
if err != nil {
panic(err)
}
nodeName, err := client.Agent().NodeName()
if err != nil {
panic(err)
}
node, _, err := client.Catalog().Node(nodeName, nil)
if err != nil {
panic(err)
}
if node == nil {
panic(err)
}
lanAddr := node.Node.TaggedAddresses["lan"]
wanAddr := node.Node.TaggedAddresses["wan"]
if lanAddr == "" || wanAddr == "" {
panic(err)
}
address := node.Node.Address
checkCfg := &api.AgentServiceCheck{
Interval: "5s",
HTTP: fmt.Sprintf("http://%s:%d/health", node.Node.Address, port),
Timeout: "10s",
DeregisterCriticalServiceAfter: "1m",
}
srvId := fmt.Sprintf("%s-%d", name, time.Now().Unix())
err = client.Agent().ServiceRegister(&api.AgentServiceRegistration{
ID: srvId,
Name: name,
Address: address,
Port: int(port),
Check: checkCfg,
Tags: []string{"urlprefix-testfabio/hello"},
})
if err != nil {
panic(err)
}
defer func() {
client.Agent().ServiceDeregister(srvId)
}()
http.HandleFunc("/health", func(http.ResponseWriter, *http.Request) {
fmt.Println("got health check")
})
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
})
http.HandleFunc("/other", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "other")
})
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
运行代码
三 检验
1 curl -v http://127.0.0.1:9999/hello
404
2 curl -v http://127.0.0.1:9999/hello -H 'Host:testfabio'
hello
3 curl -v http://127.0.0.1:9999/other -H 'Host:testfabio'
404