微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Go:grpc

一、grpc安装

将 https://github.com/google/go-genproto 放到 $GOPATH/src/google.golang.org/genproto
将 https://github.com/grpc/grpc-go       放到 $GOPATH/src/google.golang.org/grpc
将 https://github.com/golang/text        放到 $GOPATH/src/golang.org/x/text
将 https://github.com/golang/net         放到 $GOPATH/src/golang.org/x/net

然后
cd $GOPATH/src/ 
go install google.golang.org/grpc

PS:protobuf的安装不做介绍。

二、grpc的helloworld示例

服务端:

分享图片

package main

import (
    "context"
    "log"
    "net"

    "google.golang.org/grpc"
    pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
    port = ":8080"
)

// server用于实现helloworld.GreeterServer
type server struct{}

// SayHello实现了helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context,in *pb.HelloRequest) (*pb.HelloReply,error) {
    log.Printf("Received: %v",in.Name)
    return &pb.HelloReply{Message: "Hello " + in.Name},nil
}

func main() {
    // 监听
    lis,err := net.Listen("tcp",port)
    if err != nil {
        log.Fatalf("Failed to listen: %v",err)
    }
    // new服务对象
    s := grpc.NewServer()
    // 注册服务
    pb.RegisterGreeterServer(s,&server{})
    if err := s.Serve(lis); err != nil {
        log.Fatalf("Failed to serve: %v",err)
    }
}
View Code

客户端:

分享图片

package main

import (
    "context"
    "log"
    "time"

    "google.golang.org/grpc"
    // 引用编译好的protobuf文件
    pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
    address     = "localhost:8080"
    name = "World"
)

func main() {
    // 建立与服务器的连接
    conn,err := grpc.Dial(address,grpc.WithInsecure())
    if err != nil {
        log.Fatalf("连接失败: %v",err)
    }
    defer conn.Close()
    // 调用protobuf的函数创建客户端连接句柄
    c := pb.NewGreeterClient(conn)

    ctx,cancel := context.WithTimeout(context.Background(),time.Second)
    defer cancel()
    // 调用protobuf的SayHello函数
    r,err := c.SayHello(ctx,&pb.HelloRequest{Name: name})
    if err != nil {
        log.Fatalf("调用SayHello失败: %v",err)
    }
    log.Println(r.Message)
}
View Code

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐