微信搜索superit|邀请体验:大数据, 数据管理、OLAP分析与可视化平台 | 赞助作者:赞助作者

go+etcd+grpc服务发现和调用

go aide_941 9℃
package main

/**
go+etcd+grpc服务发现和调用,,etcd集群
*/
import (
    "google.golang.org/grpc"
    "context"
    "log"
    "time"
    "strconv"
    "github.com/coreos/etcd/clientv3"
    "fmt"
    "encoding/json"
    "sync"
    "math/rand"
    //"github.com/davecgh/go-spew/spew"
)

func main() {
    grpcClient := NewGrpcClient("10.xxx.xx.xx.x", 32777, "/zarten")
    ip := grpcClient.GetRrpcServIp()
    fmt.Println(ip)

    conn, err := grpc.Dial(grpcClient.GetRrpcServIp(), grpc.WithInsecure(), grpc.WithBlock())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()

    // client := go_protoc.NewZartenClient(conn)
    // res, _ := client.GetInfo(context.Background(), &go_protoc.ZartenRequest{ZhihuName:"zarten456"})
    // fmt.Println(res.Name)
    // fmt.Println(res.Homepage)

}

type GrpcClient struct {
    Etcd3Client *clientv3.Client
    GrpcEndpoints []string
}

var mu sync.Mutex

func NewGrpcClient(EtcdIp string, EtcdPort int, EtcdPrefix string) *GrpcClient{
    keyName := EtcdPrefix+"/grpc"

    grpcClient := new(GrpcClient)
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{EtcdIp + ":" + strconv.Itoa(EtcdPort)},
        DialTimeout: 10 * time.Second,
    })
    if err != nil {
        log.Fatal(err)
    }

    res, err := cli.Get(context.Background(), keyName)
    if err != nil{
        log.Fatal(err)
    }

    for _, ev := range res.Kvs {
        endPoints := ev.Value

        err := json.Unmarshal(endPoints, &grpcClient.GrpcEndpoints)
        if err != nil{
            log.Fatal(err)
        }
        break
    }
    if len(grpcClient.GrpcEndpoints) <= 0{
        log.Fatal("No grpc services are available.Please notify the administrator to start the grpc service")
    }

    grpcClient.Etcd3Client = cli

    //监听机制
    rch := cli.Watch(context.Background(), keyName)
    go func() {
        for wresp := range rch {
            for _, ev := range wresp.Events {
                fmt.Printf("%s %q : %qn", ev.Type, ev.Kv.Key, ev.Kv.Value)
                mu.Lock()
                err := json.Unmarshal(ev.Kv.Value, &grpcClient.GrpcEndpoints)
                mu.Unlock()
                if err != nil{
                    log.Fatal(err)
                }
                fmt.Println(grpcClient.GrpcEndpoints)
            }
        }
    }()

    return grpcClient
}

func (g *GrpcClient) GetRrpcServIp() string{
    rand.Seed(time.Now().Unix())
    n := len(g.GrpcEndpoints)
    return g.GrpcEndpoints[rand.Intn(n)]
}

 

转载请注明:SuperIT » go+etcd+grpc服务发现和调用

喜欢 (0)or分享 (0)