參考: http://doc.oschina.net/grpc?t=60133
https://blog.51cto.com/13914991/2309916?source=dra
https://github.com/gin-gonic/examples/blob/master/grpc/README.md
1.安裝 protoc.exe
下載頁面: https://github.com/protocolbuffers/protobuf/releases

下載windows版本protoc
解壓后加到 %PATH%路徑
2.安裝 protoc-gen-go : go語言版本的 代碼生成器
# 安裝 go 插件
go get -u github.com/golang/protobuf/protoc-gen-go

protoc-gen-go
安裝完成后, 會在
$GOPATH/bin下多一個執(zhí)行文件, 確保這個路徑也在 %PATH%下
3.準備一個 proto 文件
syntax = "proto3";
message HelloRequest {
string greeting = 1;
}
message HelloResponse {
string reply = 1;
}
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse) {
}
}
4.生成代碼
在項目目錄下執(zhí)行命令:
protoc --go_out=plugins=grpc:. protos/order.proto

生成代碼
成功后, 會生成一個 .pb.go 文件
5.編寫服務(wù)端代碼
package main
import (
"fmt"
"log"
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
order "grpc_demo/protos"
)
type Server struct{}
// SayHello (HelloRequest) returns (HelloResponse)
func (s *Server) SayHello(ctx context.Context, in *order.HelloRequest) (*order.HelloResponse, error) {
return &order.HelloResponse{Reply: "Hello :" + in.Greeting}, nil
}
func main() {
listener, e := net.Listen("tcp", ":50000")
if e != nil {
log.Fatalf("failed to listen : %v", e)
}
s := grpc.NewServer()
order.RegisterHelloServiceServer(s, &Server{})
reflection.Register(s)
if e := s.Serve(listener); e != nil {
log.Fatalf("failed to serve : %v", e)
}
fmt.Println("Server started ...")
}
6.客戶端代碼
包含兩部分: grpc的客戶端(長連接), 還有一個對外的 http 服務(wù)
package main
import (
"log"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
order "grpc_demo/protos"
)
func main() {
conn, e := grpc.Dial("localhost:50000", grpc.WithInsecure())
if e != nil {
log.Fatalf("can't connect : %v", e)
}
defer conn.Close()
client := order.NewHelloServiceClient(conn)
r := gin.Default()
r.GET("/hi/:name", func(c *gin.Context) {
name := c.Param("name")
req := &order.HelloRequest{Greeting: name}
if resp, e := client.SayHello(c, req); e == nil && resp != nil {
c.String(200, resp.Reply)
} else {
c.String(200, "something wrong")
}
})
_ = r.Run(":80")
}
7,啟動驗證

啟動服務(wù)
# 啟動服務(wù)端
go run server.go
# 啟動客戶端
go run client.go
訪問 http://localhost/hi/國服最坑開發(fā)
可以正常訪問, 則表示通路驗證完成.

http請求
8. 小結(jié)
protoc是一個通用命令, 可以生成多個語言版本的代碼.
第二步安裝的工具, 見名知義, 用于生成go語言版本時使用.
接下來,兩個方向 :
- 學(xué)習(xí)復(fù)雜結(jié)構(gòu)的消息接口定義
- 體驗其他類型的調(diào)用方式(流式/雙向流)
- 和
java語言接口互調(diào)?