1、
(1)Protocol Buffers(简称protobuf)用于结构化数据和字节码之间互相转换(即实现从结构体转换为字节流以及从字节流转换为结构体),一旦你定义了自己的报文格式(message),你就可以运行ProtocolBuffer编译器,将你的.proto文件编译成特定语言的类。
(2)proto里的message,pb.go里的结构体(带方法)
proto里的service,pb.go里Client API for Events service处供客户端使用的接口定义、接口实例、接口实例的初始化函数。Server API for Events service处供服务端使用的接口定义,注册函数。如果其中某一端或同时两端为流式RPC,在有流的一端,会专门为其流生成接口定义、接口实例。可以直接使用生成的实例,也可以自己实现接口,自定义实例。接口定义的主要方法就是Send和Recv。
(3)GRPC的Client与Server,均通过Netty Channel作为数据通信;序列化、反序列化则使用Protobuf,每个请求都将被封装成HTTP2的Stream,在整个生命周期中,客户端Channel应该保持长连接,而不是每次调用重新创建Channel、响应结束后关闭Channel(即短连接、交互式的RPC),目的就是达到链接的复用,进而提高交互效率。
(4)服务端用pb.go里的方法主要有注册;客户端用pb.go主要用生成客户端实例,再调用实例的方法。
2、https://github.com/protocolbuffers/protobuf/releases,下载protocol buffer编译器protoc,找到对应的系统版本,如linux下为x86_64。下载后解压,将bin目录下的可执行文件放到系统环境变量$GOPATH/bin下。
3、$GOPATH:go get -u github.com/golang/protobuf/protoc-gen-go,获取protol buffer的编译器插件protoc-gen-go,gRPC 提供 protocol buffer 编译插件,能够从一个服务定义的 .proto 文件生成客户端和服务端代码。
4、$GOPATH:go get github.com/golang/protobuf/proto,将库源码拉到本地,执行此命令时会自动下载库依赖。
5、go build github.com/golang/protobuf/proto,进行编译。
(github源码:https://github.com/grpc/grpc-go)
6、git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
7、git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net
8、git clone https://github.com/golang/sys.git $GOPATH/src/golang.org/x/sys
9、git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text
10、git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
再做一个Demo:
新建工程grpcT,目录如上。
1.common.proto内容:
syntax = "proto3";
package common;
service UserService {
rpc GetUser (GetUserRequest) returns (GetUserResponse);
}
message GetUserRequest {
int64 id = 1;
}
message ImageObj {
int64 id = 1;
int64 index = 2;
string url = 3;
}
message UserObj {
int64 id = 1;
string name = 2;
repeated ImageObj images = 3;
// []*images images = 10;
}
message GetUserResponse {
UserObj res = 1;
int64 errcode = 2;
}
使用protoc --go_out=plugins=grpc:. common.proto 生成.pb.go文件
然后开发相应的server和client
client.go:
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"test/grpc_test/common"
"time"
"google.golang.org/grpc"
)
func main() {
//建立链接
conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := common.NewUserServiceClient(conn)
// Contact the server and print out its response.
var id int64 = 1
if len(os.Args) > 1 {
id, _ = strconv.ParseInt(os.Args[1], 10, 64)
}
// 1秒的上下文
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.GetUser(ctx, &common.GetUserRequest{Id: id})
if err != nil {
log.Fatalf("could not getUser: %v", err)
}
fmt.Println(r.Res.Id)
fmt.Println(r.Res.Name)
fmt.Println(r.Res.Images[1])
log.Printf("GetUser: %s", r)
}
server.go
package main
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"log"
"net"
"test/grpc_test/common"
)
const (
Address = "localhost:8080"
)
type server struct {
}
func (s *server) GetUser(ctx context.Context, in *common.GetUserRequest) (*common.GetUserResponse, error) {
var images []*common.ImageObj
for i := 0; i < 5; i++ {
images = append(images, &common.ImageObj{Id: 1, Index: 1})
}
return &common.GetUserResponse{Errcode: 0, Res: &common.UserObj{Id: 1, Name: "zhouyu", Images: images}}, nil
}
//listen,server on
func main() {
listen, err := net.Listen("tcp", Address)
if err != nil {
log.Fatal("failed to listen: %v", err)
}
s := grpc.NewServer()
common.RegisterUserServiceServer(s, &server{})
// 注册反射服务 这个服务是CLI使用的 跟服务本身没有关系
reflection.Register(s)
if err := s.Serve(listen); err != nil {
log.Fatalf("failed to server: %v", err)
}
}