diff --git a/consul/consul-service.go b/consul/consul-service.go index eb85814..789b07a 100644 --- a/consul/consul-service.go +++ b/consul/consul-service.go @@ -12,7 +12,7 @@ const ( ) //Register 注册服务到consul -func Register(id string, name string, addr string, port int, tags ...string) { +func Register(name string, addr string, port int, tags ...string) { // 创建连接consul服务配置 config := consulapi.DefaultConfig() config.Address = consulAddr @@ -26,7 +26,7 @@ func Register(id string, name string, addr string, port int, tags ...string) { // 创建注册到consul的服务到 registration := new(consulapi.AgentServiceRegistration) - registration.ID = id + registration.ID = fmt.Sprintf("%s-%s:%d", name, addr, port) registration.Name = name registration.Port = port registration.Tags = tags @@ -49,7 +49,7 @@ func Register(id string, name string, addr string, port int, tags ...string) { } //DeRegister 取消consul注册的服务 -func DeRegister(name string) { +func DeRegister(name string, addr string, port int) { // 创建连接consul服务配置 config := consulapi.DefaultConfig() config.Address = consulAddr @@ -60,7 +60,7 @@ func DeRegister(name string) { }).Errorf("%v", err) } - client.Agent().ServiceDeregister(name) + client.Agent().ServiceDeregister(fmt.Sprintf("%s-%s:%d", name, addr, port)) } //FindServer 从consul中发现服务 diff --git a/main.go b/main.go index 9ab0734..eb989f5 100644 --- a/main.go +++ b/main.go @@ -8,7 +8,6 @@ import ( "net" "os" "os/signal" - "strconv" "time" "google.golang.org/grpc" @@ -39,7 +38,7 @@ func main() { // grpc服务启动 go func() { - log.Printf("starting grpc service on %s\n", *addr) + log.Printf("starting grpc service on %s:%d\n", *addr, *port) lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *addr, *port)) if err != nil { log.Fatal("fail to open port: ", err) @@ -51,8 +50,8 @@ func main() { }() //注册至consul - consul.Register(APPNAME+strconv.Itoa(*port), APPNAME, *addr, *port, "demo") - defer consul.DeRegister(APPNAME) + consul.Register(APPNAME, *addr, *port, "demo") + defer consul.DeRegister(APPNAME, *addr, *port) // 服务停止相应 c := make(chan os.Signal, 1)