golang 同時(一個專案)註冊http和GRPC服務

酒沉吟發表於2024-06-16

main 裡面

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/hashicorp/consul/api"
    grpc "gorm_project/grpc/services"
    "gorm_project/route"
    "gorm_project/utils"
    "log"
    "net/http"
)

func main() {
    // **************協程開始Grpc服務 **************************
    go grpc.RunGrpc()
    utils.InitRedisClient()
    r := gin.Default()
    // ****** consul健康檢查服務 *******
    r.GET("/health", func(c *gin.Context) { c.String(http.StatusOK, "OK") })
    //r.Use(middleware.ValiTokenMiddleware())
    route.AddGoodsRoute(r)
    route.AddOrderInfo(r)
    // *************註冊服務到consul **********************
    client, regId, err := ConsulRegister()
    if err != nil {
        return
    } else { // 登出 consul 服務
        defer client.Agent().ServiceDeregister(regId)
    }
    r.Run(":8595")
}

// ***************註冊服務到consul 方法***********************
func ConsulRegister() (*api.Client, string, error) {
    // 建立Consul客戶端
    config := api.DefaultConfig()
    config.Address = "39.101.194.250:8500" // Consul伺服器地址
    client, err := api.NewClient(config)
    if err != nil {
        log.Fatal(err)
    }
    // 註冊服務到consul
    reg := new(api.AgentServiceRegistration)
    reg.ID = "httpgrpc-http-service-id"
    reg.Name = "httpgrpc-http"
    reg.Tags = []string{"httpgrpc-http"}
    reg.Port = 8595
    reg.Address = "127.0.0.1"
    reg.Check = &api.AgentServiceCheck{
        HTTP:                           fmt.Sprintf("http://localhost:%d/health", reg.Port),
        Timeout:                        "5s",
        Interval:                       "10s",
        DeregisterCriticalServiceAfter: "30s",
    }
    err = client.Agent().ServiceRegister(reg)
    return client, reg.ID, err
}

協程裡的GRPC 註冊到consul

package grpc

import (
    "context"
    "fmt"
    "github.com/hashicorp/consul/api"
    pb "gorm_project/grpc/services/proto"
    "log"
    "net"

    "google.golang.org/grpc"
)

type Server struct {
    pb.UnimplementedGreeterServer
}

func (s *Server) SayHello(cxt context.Context, r *pb.HelloRequest) (h *pb.HelloReply, e error) {
    return &pb.HelloReply{Message: "好樣的"}, nil
}

func RunGrpc() {
    fmt.Println("開始監聽了~~~~~")
    // 1.開始監聽
    listen, err := net.Listen("tcp", ":9868")
    if err != nil {
        fmt.Println("listen err:", err)
        return
    }
    defer listen.Close()
    // 2.建立GRPC 服務
    server := grpc.NewServer()
    // 3.將服務和例項註冊 ******** 注意 pb 取於.proto 裡的 option go_package = "./;pb";  ********
    pb.RegisterGreeterServer(server, &Server{})
    // *************註冊服務到consul **********************
    client, regId, err := ConsulRegister()
    if err != nil {
        return
    } else { // 登出 consul 服務
        defer client.Agent().ServiceDeregister(regId)
    }
    // 4.服務開始監聽
    errs := server.Serve(listen)
    if errs != nil {
        fmt.Println("服務出錯 err:", err)
        return
    }
    //time.Sleep(time.Second * 10)
}

// ***************註冊服務到consul 方法***********************
func ConsulRegister() (*api.Client, string, error) {
    // 建立Consul客戶端
    config := api.DefaultConfig()
    config.Address = "39.101.194.250:8500" // Consul伺服器地址
    client, err := api.NewClient(config)
    if err != nil {
        log.Fatal(err)
    }
    // 註冊服務
    reg := new(api.AgentServiceRegistration)
    reg.ID = "httpgrpc-grpc-service-id"
    reg.Name = "httpgrpc-grpc"
    reg.Tags = []string{"httpgrpc-grpc"}
    reg.Port = 8595
    reg.Address = "127.0.0.1"
    reg.Check = &api.AgentServiceCheck{
        HTTP:                           fmt.Sprintf("http://localhost:%d/health", reg.Port),
        Timeout:                        "5s",
        Interval:                       "10s",
        DeregisterCriticalServiceAfter: "30s",
    }
    err = client.Agent().ServiceRegister(reg)
    return client, reg.ID, err
}

效果

相關文章