go服务发现-consul

242 阅读1分钟

1、服务注册

package mainimport (    "flag"    "fmt"    "net"    "os"    "os/signal"    "syscall"    "github.com/hashicorp/consul/api"    uuid "github.com/satori/go.uuid"    "go.uber.org/zap"    "google.golang.org/grpc"    "google.golang.org/grpc/health"    "google.golang.org/grpc/health/grpc_health_v1")

//consul 的ip地址和端口 type ConsulInfo struct {    Host string `mapstructure:"host" json:"host"`    Port int    `mapstructure:"port" json:"port"`}func main() {    Port := flag.Int("port", 0, "端口号")//服务启动的端口地址/可以是命令行传递过来的    flag.Parse()



    // 注册服务健康检查    grpc_health_v1.RegisterHealthServer(server, health.NewServer())    //服务注册    cfg := api.DefaultConfig()    cfg.Address = fmt.Sprintf("%s:%d", ConsulInfo.Host,       ConsulInfo.Port)    client, err := api.NewClient(cfg)    if err != nil {        panic(err)    }    //生成对应的检查对象    check := &api.AgentServiceCheck{        GRPC:                           fmt.Sprintf("本机/部署服务器的ip:%d", *Port),        Timeout:                        "5s",        Interval:                       "5s",        DeregisterCriticalServiceAfter: "15s",    }    //生成注册对象
    //1. 如何启动两个服务 //2. 即使我能够通过终端启动两个服务,但是注册到consul中的时候也会被覆盖      3、使用动态id  uuid生成     registration := new(api.AgentServiceRegistration)    registration.Name = 服务的名字    serviceID := fmt.Sprintf("%s", uuid.NewV4())//可注册多个服务 uuid    registration.ID = serviceID    registration.Port = *Port//服务的端口号    registration.Tags = []string{"user", "srv"}//服务的tag    registration.Address = "192.168.1.10"//本机/部署服务器的ip    registration.Check = check        err = client.Agent().ServiceRegister(registration)    if err != nil {        panic(err)    }    func() {        err = server.Serve(lis)        if err != nil {            panic("failed to start grpc:" + err.Error())        }    }()    //接收终止信号    quit := make(chan os.Signal)    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)    <-quit    if err = client.Agent().ServiceDeregister(serviceID); err != nil {        zap.S().Info("注销失败")    }    zap.S().Info("注销成功")}

发现服务

 package mainimport (    "fmt"    "github.com/hashicorp/consul/api"    _ "github.com/mbobakov/grpc-consul-resolver" // It's important    "go.uber.org/zap"    "google.golang.org/grpc")
type consulInfostruct {            Host string `mapstructure:"host" json:"host"`           Port int    `mapstructure:"port" json:"port"`          }//从注册中心获取用户服务  无负载均衡
func  main(){
    cfg := api.DefaultConfig()    consulInfo := global.ServerConfig.ConsulInfo    cfg.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)    userSrvHost := ""    userSrvPort := 0    client, err := api.NewClient(cfg)    if err != nil {        panic(err)    }    data, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service==\"%s\"", 服务的名字//registration.Name))    if err != nil {        panic(err)    }    for _, value := range data {        userSrvHost = value.Address        userSrvPort = value.Port        break    }    if userSrvHost == "" {        return    }    useConn, err := grpc.Dial(fmt.Sprintf("%s:%d", userSrvHost, userSrvPort), grpc.WithInsecure())    if err != nil {            "msg", err.Error())    }    userSrvClient := proto.NewUserClient(useConn)    xxxx= userSrvClient//赋值到全部变量xx供接口调用
}