前言
grpc 是一種基于
HTTP/2
設(shè)計的RPC框架枷颊,采用protobuf作為idl
(交互式數(shù)據(jù)語言Interactive Data Language)
本篇簡單介紹下grpc的使用中贝,并制作一個demo
一聋庵、安裝protoc
$ go get -u github.com/golang/protobuf
$ go get -u github.com/golang/protobuf/protoc-gen-go
- 確保protoc protoc-gen-go安裝成功星压,可到$GOPATH/bin/ 目錄下查看
二、項目創(chuàng)建
1.創(chuàng)建目錄結(jié)構(gòu)
hello
├── client
│ └── client.go
└── server
└── server.go
└── proto
└── hello.proto
└── hello.pb.go # 通過protoc命令生成
├── go.mod
編寫proto文件
// hello.proto
syntax = "proto3";
service HelloService {
rpc SayHello(SayHelloRequest)returns(SayHelloResponse){}
}
message SayHelloRequest{
string name = 1;
}
message SayHelloResponse {
string msg = 1;
}
生成pb文件 proto/hello.pb.go
$ protoc --go_out=plugins=grpc:./ ./proto/hello.proto
2 編寫服務(wù)端代碼
// server/server.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
hello "hello/proto"
"log"
"net"
)
type HelloServer struct {
}
func (h *HelloServer) SayHello(ctx context.Context, request *hello.SayHelloRequest) (*hello.SayHelloResponse, error) {
name := request.Name
fmt.Printf("receive name : %s", name)
msg := fmt.Sprintf("hello, %s", name)
return &hello.SayHelloResponse{Msg: msg}, nil
}
func main() {
server := grpc.NewServer() // 創(chuàng)建gRPC Server 對象
// 將HelloService 注冊到gRPC Server 的內(nèi)部注冊中心哼拔;接收到請求時盖呼,通過內(nèi)部的服務(wù)發(fā)現(xiàn),發(fā)現(xiàn)該服務(wù)的端口并轉(zhuǎn)接進行邏輯處理
hello.RegisterHelloServiceServer(server,&HelloServer{})
// 創(chuàng)建listen弧岳,監(jiān)聽tcp端口
lis, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("failed to listen:%+v", err)
}
if err := server .Serve(lis); err != nil {
log.Fatalf("err %+v", err)
}
}
3 編寫客戶端代碼
// client/client.go
package main
import (
"context"
"google.golang.org/grpc"
hello "hello/proto"
"log"
)
const (
Address = "127.0.0.1:8080"
)
func main() {
conn, err := grpc.Dial(Address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
client := hello.NewHelloServiceClient(conn)
ctx := context.Background()
request := &hello.SayHelloRequest{Name: "lester"}
response, err := client.SayHello(ctx, request)
if err != nil {
log.Fatalf("get response err :%v", err)
}
log.Printf("receive response msg:%s", response.Msg)
}
- 根目錄下運行
go run server/server.go
- 另起一個終端運行
go run client/client.go
客戶端輸出結(jié)果