package main import ( "flag" "fmt" "github.com/google/uuid" "github.com/hashicorp/consul/api" "log" "net/http" "time" ) const ConsulServerAddress = "192.168.177.131:8500" func main() { // 处理命令行参数 addr := flag.String("addr", "127.0.0.1", "The Address for listen. Default is 127.0.0.1") port := flag.Int("port", 8080, "The Port for listen. Default is 8080.") flag.Parse() // 拼凑完整地址 address := fmt.Sprintf("%s:%d", *addr, *port) // 定义业务逻辑服务,假设为产品服务 service := http.NewServeMux() service.HandleFunc("/info", func(writer http.ResponseWriter, request *http.Request) { _, err := fmt.Fprintf(writer, "Product Service on %s. Now is %s", address, time.Now().String()) if err != nil { log.Fatalln(err) } }) // 增加 /health 路由处理器 service.HandleFunc("/health", func(writer http.ResponseWriter, request *http.Request) { log.Println("Health Check.") _, err := fmt.Fprintf(writer, "Product Service Health Check.") if err != nil { log.Fatalln(err) } }) // 定义注册中心的服务 serviceReg := new(api.AgentServiceRegistration) serviceReg.Name = "Product" serviceReg.ID = "productService-" + uuid.NewString() serviceReg.Address = *addr serviceReg.Port = *port serviceReg.Tags = []string{"test"} // 定义服务的健康检查 serviceReg.Checks = api.AgentServiceChecks{ &api.AgentServiceCheck{ CheckID: serviceReg.ID + "-check", Name: serviceReg.ID + "-check", Interval: "5s", Timeout: "1s", HTTP: fmt.Sprintf("http://%s/health", address), Method: "GET", Notes: "", SuccessBeforePassing: 0, FailuresBeforeWarning: 0, FailuresBeforeCritical: 0, DeregisterCriticalServiceAfter: "", }, } // 注册服务 // 连接 consul ,作为客户端连接 consul consulApiConfig := api.DefaultConfig() consulApiConfig.Address = ConsulServerAddress consulClient, err := api.NewClient(consulApiConfig) if err != nil { log.Fatalln(err) } // 发出 put 注册请求 if err := consulClient.Agent().ServiceRegister(serviceReg); err != nil { log.Fatalln(err) } log.Println("Service Product has be registered.") // 启动监听 fmt.Printf("Product service is listening on %s.\n", address) log.Fatalln(http.ListenAndServe(address, service)) }