GRPC介紹
目錄
- 單體架構
- 微服務架構
- 問題
- 原始的grpc
- 服務端
- 客戶端
- 原生rpc的問題
- grpc的hello world
- 服務端
- 客戶端
- proto文件
- proto語法
- 數據類型
- 基本數據類型
- 其他數據類型
- 數據類型
- 編寫風格
- 多服務
單體架構
- 只能對整體擴容
- 一榮俱榮,一損俱損
- 代碼耦合,項目的開發者需要知道整個項目的流程
微服務架構
針對單體架構的問題出現了微服務架構
- 可以按照服務進行單獨擴容
- 各個服務之間可以獨立開發,獨立部署
問題
- 代碼冗余
- 服務之間的調用很麻煩
為什么要使用grpc
grpc使用的意義
原始的grpc
服務端
package mainimport ("fmt""net""net/http""net/rpc"
)type Server struct {
}
type Req struct {Num1 intNum2 int
}
type Res struct {Num int
}func (s Server) Add(req Req, res *Res) error {res.Num = req.Num1 + req.Num2return nil
}func main() {// 注冊rpc服務rpc.Register(new(Server))rpc.HandleHTTP()listen, err := net.Listen("tcp", ":8080")if err != nil {fmt.Println(err)return}http.Serve(listen, nil)
}
客戶端
package mainimport ("fmt""net/rpc"
)type Req struct {Num1 intNum2 int
}
type Res struct {Num int
}func main() {req := Req{1, 2}client, err := rpc.DialHTTP("tcp", ":8080")if (err != nil) {fmt.Println(err)return}var res Resclient.Call("Server.Add", req, &res)fmt.Println(res)
}
原生rpc的問題:
- 編寫相對復雜,需要自己去關注實現過程
- 沒有代碼提示,容易寫錯。
grpc的hello world
服務端
- 編寫一個結構體,名字叫什么不重要
- 重要的是得實現protobuf中的所有方法
- 監聽端口
- 注冊服務
package mainimport ("context""fmt""google.golang.org/grpc""google.golang.org/grpc/grpclog""grpc_study/grpc_proto/hello_grpc""net"
)type HelloServiceServer struct {
}func (s HelloServiceServer) SayHello(ctx context.Context, request *hello_grpc.HelloRequest) (res *hello_grpc.HelloResponse, err error) {fmt.Println("請求來了!", request)return &hello_grpc.HelloResponse{Message: "Hello " + "Xiaoyu_Wang",Name: "Server",}, nil
}func main() {// 監聽端口listen, err := net.Listen("tcp", ":8080")if err != nil {grpclog.Fatalf("Failed to listen: %v", err)}// 創建一個gRPC服務器實例。s := grpc.NewServer()server := HelloServiceServer{}// 將server結構體注冊為gRPC服務。hello_grpc.RegisterHelloServiceServer(s, &server)fmt.Println("grpc server running :8080")// 開始處理客戶端請求。err = s.Serve(listen)
}
客戶端
- 建立連接
- 調用方法
package mainimport ("context""fmt""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure""grpc_study/grpc_proto/hello_grpc""log"
)func main() {addr := ":8080"// 使用 grpc.Dial 創建一個到指定地址的 gRPC 連接。// 此處使用不安全的證書來實現 SSL/TLS 連接conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))if err != nil {log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 連接失敗 %s", addr, err))}defer conn.Close()// 初始化客戶端client := hello_grpc.NewHelloServiceClient(conn)result, err := client.SayHello(context.Background(), &hello_grpc.HelloRequest{Name: "Xiaoyu_Wang",Message: "ok",})fmt.Println(result, err)
}
proto文件
syntax = "proto3"; // 指定proto版本
package hello_grpc; // 指定默認包名// 指定golang包名
option go_package = "/hello_grpc";//定義rpc服務
service HelloService {// 定義函數rpc SayHello (HelloRequest) returns (HelloResponse) {}
}// HelloRequest 請求內容
message HelloRequest {string name = 1; // 消息號string message = 2;
}// HelloResponse 響應內容
message HelloResponse{string name = 1;string message = 2;
}
proto語法
- service 對應的就是go里面的接口,可以作為服務端,客戶端
- rpc 對應的就是結構體中的方法
- message對應的也是結構體
數據類型
基本數據類型
message Request {double a1 = 1;float a2 = 2;int32 a3 = 3;uint32 a4 = 4;uint64 a5 = 5;sint32 a6 = 6;sint64 a7 = 7;fixed32 a8 = 8;fixed64 a9 = 9;sfixed32 a10 = 10;sfixed64 a11 = 11;bool a12 = 12;string a13 = 13;bytes a14 = 14;
}
對應的go類型:
type Request struct {state protoimpl.MessageStatesizeCache protoimpl.SizeCacheunknownFields protoimpl.UnknownFieldsA1 float64 `protobuf:"fixed64,1,opt,name=a1,proto3" json:"a1,omitempty"`A2 float32 `protobuf:"fixed32,2,opt,name=a2,proto3" json:"a2,omitempty"`A3 int32 `protobuf:"varint,3,opt,name=a3,proto3" json:"a3,omitempty"`A4 uint32 `protobuf:"varint,4,opt,name=a4,proto3" json:"a4,omitempty"`A5 uint64 `protobuf:"varint,5,opt,name=a5,proto3" json:"a5,omitempty"`A6 int32 `protobuf:"zigzag32,6,opt,name=a6,proto3" json:"a6,omitempty"`A7 int64 `protobuf:"zigzag64,7,opt,name=a7,proto3" json:"a7,omitempty"`A8 uint32 `protobuf:"fixed32,8,opt,name=a8,proto3" json:"a8,omitempty"`A9 uint64 `protobuf:"fixed64,9,opt,name=a9,proto3" json:"a9,omitempty"`A10 int32 `protobuf:"fixed32,10,opt,name=a10,proto3" json:"a10,omitempty"`A11 int64 `protobuf:"fixed64,11,opt,name=a11,proto3" json:"a11,omitempty"`A12 bool `protobuf:"varint,12,opt,name=a12,proto3" json:"a12,omitempty"`A13 string `protobuf:"bytes,13,opt,name=a13,proto3" json:"a13,omitempty"`A14 []byte `protobuf:"bytes,14,opt,name=a14,proto3" json:"a14,omitempty"`
}
其他數據類型
- 數組類型
message ArrayRequest {repeated int64 a1 = 1;repeated string a2 = 2;repeated Request request_list = 3;
}
type ArrayRequest struct {A1 []int64 A2 []string RequestList []*Request
}
- map類型
message MapRequest {map<int64, string> m_i_s = 1;map<string, bool> m_i_b = 2;map<string, ArrayRequest> m_i_arr = 3;
}
type MapRequest struct {MIS map[int64]stringMIB map[string]boolMIArr map[string]*ArrayRequest
}
- 嵌套類型
message Q1 {message Q2{string name2 = 2;}string name1 = 1;Q2 q2 = 2;
}
type Q1 struct {state protoimpl.MessageStatesizeCache protoimpl.SizeCacheunknownFields protoimpl.UnknownFieldsName1 string `protobuf:"bytes,1,opt,name=name1,proto3" json:"name1,omitempty"`Q2 *Q1_Q2 `protobuf:"bytes,2,opt,name=q2,proto3" json:"q2,omitempty"`
}
編寫風格
- 文件名建議下劃線,例如:my_student.proto
- 包名和目錄名對應
- 服務名、方法名、消息名均為大駝峰
- 字段名為下劃線
多服務
syntax = "proto3";option go_package = "/duo_grpc";service VideoService {rpc Look (Request) returns (Response) {}
}message Request{string name = 1;
}message Response{string name = 1;
}service OderService {rpc Buy (Request) returns (Response) {}
}