consul下载地址: https://www.consul.io/downloads
traefik下载地址:https://github.com/traefik/traefik/releases
启动traefik的命令
traefik.exe --api.insecure=true --configFile=traefik-sample.yml
配置文件 traefik-sample.yml
################################################################
#
# Configuration sample for Traefik v2.
#
# For Traefik v1: https://github.com/traefik/traefik/blob/v1.7/traefik.sample.toml
#
################################################################
################################################################
# Global configuration
################################################################
global:
checkNewVersion: true
sendAnonymousUsage: true
################################################################
# EntryPoints configuration
################################################################
# EntryPoints definition
#
# Optional
#
entryPoints:
web:
address: :80
websecure:
address: :443
################################################################
# Traefik logs configuration
################################################################
# Traefik logs
# Enabled by default and log to stdout
#
# Optional
#
log:
# Log level
#
# Optional
# Default: "ERROR"
#
level: DEBUG
# Sets the filepath for the traefik log. If not specified, stdout will be used.
# Intermediate directories are created if necessary.
#
# Optional
# Default: os.Stdout
#
# filePath: log/traefik.log
# Format is either "json" or "common".
#
# Optional
# Default: "common"
#
# format: json
################################################################
# Access logs configuration
################################################################
# Enable access logs
# By default it will write to stdout and produce logs in the textual
# Common Log Format (CLF), extended with additional fields.
#
# Optional
#
#accessLog:
# Sets the file path for the access log. If not specified, stdout will be used.
# Intermediate directories are created if necessary.
#
# Optional
# Default: os.Stdout
#
# filePath: /path/to/log/log.txt
# Format is either "json" or "common".
#
# Optional
# Default: "common"
#
# format: json
################################################################
# API and dashboard configuration
################################################################
# Enable API and dashboard
#
# Optional
#
api:
# Enable the API in insecure mode
#
# Optional
# Default: false
#
insecure: true
# Enabled Dashboard
#
# Optional
# Default: true
#
# dashboard: false
################################################################
# Ping configuration
################################################################
# Enable ping
#ping:
# Name of the related entry point
#
# Optional
# Default: "traefik"
#
# entryPoint: traefik
################################################################
# Docker configuration backend
################################################################
providers:
consulCatalog:
refreshInterval: 30s
defaultRule: "PathPrefix(`/{{ .Name }}`)"
endpoint:
address: 127.0.0.1:8500
scheme: http
# Enable Docker configuration backend
# docker:
# Docker server endpoint. Can be a tcp or a unix socket endpoint.
#
# Required
# Default: "unix:///var/run/docker.sock"
#
# endpoint: tcp://10.10.10.10:2375
# Default host rule.
#
# Optional
# Default: "Host(`{{ normalize .Name }}`)"
#
# defaultRule: Host(`{{ normalize .Name }}.docker.localhost`)
# Expose containers by default in traefik
#
# Optional
# Default: true
#
# exposedByDefault: false
启动consul服务:
consul.exe agent -dev -ui
启动go 服务,并注册到consul:
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
"time"
consulapi "github.com/hashicorp/consul/api"
)
var port = 12000
var http_pre = "/consulServerNode"
// consul 服务端会自己发送请求,来进行健康检查
func consulCheck(w http.ResponseWriter, r *http.Request) {
s := "consulCheck" + fmt.Sprint(time.Now()) + " remote:" + r.RemoteAddr + " " + r.URL.String()
_, _ = fmt.Fprintln(w, s)
}
func HelloHandle(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, " hello! port = 12000")
}
func registerServer() {
config := consulapi.DefaultConfig()
client, err := consulapi.NewClient(config)
if err != nil {
panic(err)
}
registration := &consulapi.AgentServiceRegistration{
ID: "consulServerNode_1",
Name: "consulServerNode",
Tags: []string{"traefik-test-tag"},
Port: port,
Address: "127.0.0.1",
}
registration.Check = &consulapi.AgentServiceCheck{ // 健康检查
HTTP: fmt.Sprintf("http://%s:%d%s", registration.Address, port, http_pre +"/check"),
Timeout: "3s",
Interval: "5s", // 健康检查间隔
DeregisterCriticalServiceAfter: "30s", //check失败后30秒删除本服务,注销时间,相当于过期时间
}
if err := client.Agent().ServiceRegister(registration);err != nil {
panic(err)
}
http.HandleFunc(http_pre +"/check", consulCheck)
http.HandleFunc(http_pre +"/hello", HelloHandle)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err!= nil{
panic(err)
}
}
func main() {
registerServer()
}
启动traefik服务,启动命令见文章开始处
启动时会看到这样的日志(为看的比较清晰,将一些\" 替换成了“)
level=debug msg="Configuration received from provider consulcatalog: {"http":{"routers":{"consul":{"service":"consul","rule":"PathPrefix(`/consul`)"},"consulServerNode":{"service":"consulServerNode","rule":"PathPrefix(`/consulServerNode`)"}},"services":{"consul":{"loadBalancer":{"servers":[{"url":"http://127.0.0.1:8300"}],"passHostHeader":true}},"consulServerNode":{"loadBalancer":{"servers":[{"url":"http://127.0.0.1:12000"}],"passHostHeader":true}}}},"tcp":{},"udp":{}}" providerName=consulcatalog
浏览器访问 http://127.0.0.1/consulServerNode/hello
参考链接: