0x00 前言
本文內(nèi)容包括:
- 用go語言實現(xiàn)一個grpc的hello服務(wù)
- 通過kong為grpc服務(wù)添加一個接口配置項
- 命令行方式測試grpc接口服務(wù)
注意: 本文只記錄了Kong相關(guān)的配置, Go
相關(guān)內(nèi)容沒有過多詳細(xì)介紹, 見諒.
0x01 Kong升級安裝
nginx 1.3.10 以后版本官方支持grpc協(xié)議, 所以, 本文開始要使用的Kong版本為 1.3.0.
由于之前教程里一直使用的是1.2.x 版本, 這里記錄一下升級過程.
# 查詢可用版本
yum provides kong
# 安裝 1.3.0 版本
yum install kong-1.3.0-1.x86_64
接下來, 第一次使用 kong restart
重啟服務(wù)時, 會提示一些數(shù)據(jù)庫格式不兼容的信息.
但只需要根據(jù)提示輸入遷移數(shù)據(jù)庫的指令即可完成.(具體指令忘記了記錄 :)
再次 kong restart
完成升級
0x02 grpc 服務(wù)
go
語言寫grpc
還是比較簡單的(相比Java
代碼少了很多). 這里只記錄一下用到的代碼 ,具體實施過程 不是本文重點.
- 定義一個proto
syntax = "proto3";
message HelloRequest {
string greeting = 1;
}
message HelloResponse {
string reply = 1;
}
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse) {
}
}
- 生成
go
代碼
protoc --go_out=plugins=grpc:. protos/order.proto
- 編寫服務(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 ...")
}
- 啟動服務(wù)
go run server.go
目錄結(jié)構(gòu)
到此, 我們就有一個端口為50000
的grpc服務(wù).
0x03 配置Kong
-
添加一個
service
Service -
為此
service
添加一個router
Router
重點已經(jīng)給出來了, 記得Paths
和 Protocols
這里輸入好字符后, 要回車一下.
OK, Kong已經(jīng)配置完成, 是不是很簡單.
0x04 安裝grpc
命令行工具grpcurl
go get github.com/fullstorydev/grpcurl
go install github.com/fullstorydev/grpcurl/cmd/grpcurl
grpcurl
-
grpcurl
使用基礎(chǔ)
下圖展示的是通過grpcurl
來查看服務(wù)的細(xì)節(jié)
- 查看有哪些服務(wù)
grpcurl -plaintext localhost:80 list- 查看服務(wù)有哪些方法
grpcurl -plaintext localhost:80 list HelloService- 查看方法定義
grpcurl -plaintext localhost:80 describe HelloService.SayHello- 查看參數(shù)定義
grpcurl -plaintext localhost:80 describe HelloRequest- 構(gòu)建參數(shù), 發(fā)啟調(diào)用
grpcurl -d '{"greeting":"國服最坑開發(fā)"}' -plaintext localhost:80 HelloService.SayHello
grpcurl使用基礎(chǔ)
0x05 驗證接口
grpcurl -v -d '{"greeting":"world"}' -plaintext localhost:80 HelloService.SayHello
請求過程
完美!!!