启动服务consul_conf的json文件看https://www.cnblogs.com/topass123/p/16993018.html

consul agent -server -dev -ui -client 0.0.0.0 -config-dir=C:\Users\86185\go\consul_conf

 

启动server

package main

import (
    "context"
    "fmt"
    say "go_redis/grpc_pg"
    "google.golang.org/grpc"
    "net"
)

type User struct {
}

func (u *User) SayHello(ctx context.Context, in *say.SayRequest) (*say.SayResponse, error) {
    resp := say.SayResponse{Ret:"hello "+in.Name}
    return &resp,nil
}

func main() {
    server := grpc.NewServer()
    say.RegisterSayServiceServer(server,&User{})
    listen, err := net.Listen("tcp", "127.0.0.1:8080")
    fmt.Println("开始监听8080")
    if err != nil {
        fmt.Println("network error")
    }
    server.Serve(listen)
}

 

启动client;下载go get github.com/hashicorp/consul/api

package main

import (
    "context"
    "fmt"
    "github.com/hashicorp/consul/api"
    say "go_redis/grpc_pg"
    "google.golang.org/grpc"
)

func main() {
    config := api.DefaultConfig()
    config.Address = "127.0.0.1:8500"

    var waitIndex uint64
    client_api,_ := api.NewClient(config)
    services,_,_ := client_api.Health().Service("hello","uth",true,&api.QueryOptions{
        WaitIndex:waitIndex,
    })
    address := services[0].Service.Address
    port := services[0].Service.Port

    url := fmt.Sprintf("%s:%d",address,port)
    fmt.Println(url)
    conn,err:=grpc.Dial(url,grpc.WithInsecure())

    //conn,err:=grpc.Dial("127.0.0.1:8080",grpc.WithInsecure())
    if err !=nil{
        fmt.Println(err)
    }
    client:=say.NewSayServiceClient(conn)
    resp,err:=client.SayHello(context.Background(),&say.SayRequest{Name: "taipi"})
    if err !=nil{
        fmt.Println(err)
    }
    fmt.Println(resp.Ret)

}

 

posted on 2022-12-19 20:39  topass123  阅读(15)  评论(0编辑  收藏  举报