Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of gRPC?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

What is the principle of gRPC, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

What is gRPC?

What is gRPC? Can be summed up in a sentence on the official website: a high-performance, open-source universal RPC framework.

The so-called RPC (remote procedure call remote procedure call) framework actually provides a mechanism that enables applications to communicate with each other and also conforms to the server/client model. When in use, the client calls the interface provided by the server as if it were calling a local function. The following figure shows a typical RPC structure diagram.

GRPC vs Restful API

Both gRPC and restful API provide a communication mechanism for server/client model communication, and both use http as the underlying transport protocol (strictly speaking, gRPC uses http2.0, while restful api is not necessarily). However, gRPC still has some unique advantages, as follows:

GRPC can define interfaces through protobuf so that there can be more stringent interface constraints. For more information on protobuf, see the next Protobuf brief tutorial. In addition, protobuf allows you to serialize data to binary encoding, which greatly reduces the amount of data that needs to be transferred, thus greatly improving performance.

GRPC can easily support streaming communication (in theory, you can use streaming mode through http2.0, but usually the restful api of web services seems to be rarely used like this. General streaming data applications such as video streaming generally use special protocols such as HLS,RTMP, etc., these are not our usual web services, but there are special server applications. )

Working with scen

When we need to strictly restrict the interface, for example, we provide a public service, and many people, even people outside the company, can access this service. Then we want to have more stringent restrictions on the interface. We do not want the client to pass arbitrary data to us, especially considering the security factors, we usually need to impose more stringent constraints on the interface. At this point, gRPC can provide strict interface constraints through protobuf.

When there are higher requirements for performance. Sometimes our services need to transfer a large amount of data, but do not want to affect our performance, we can also consider gRPC services, because through protobuf we can convert data compression into binary format, usually the amount of data transferred is much smaller, and through http2 we can achieve asynchronous requests, thus greatly improving the efficiency of communication.

However, usually we do not use gRPC alone, but use gRPC as a component, because in the production environment, we need to use a distributed system to deal with large concurrency, while gRPC does not provide some necessary components related to the distributed system. Moreover, real online services also need to provide necessary components, including load balancing, current-limiting circuit breakers, monitoring alarms, service registration and discovery, and so on. However, this is not the topic of this article, so let's move on to how to use gRPC.

Detailed explanation of gRPC DEMO examples

Define interfaces and data types through protobuf

Write gRPC server side code

Write gRPC client side code

This article uses golang to implement demo, in which the installation of protobuf and grpc extensions is skipped.

Create a new userrpc.proto

Syntax = "proto3"; package user;option go_package = ". / grpc/user"; / / The User service definition.service User {/ / Get all Users with id-A server-to-client streaming RPC. Rpc GetUsers (UserFilter) returns (stream UserRequest) {} / / Create a new User-A simple RPC rpc CreateUser (UserRequest) returns (UserResponse) {}} / / Request message for creating a new usermessage UserRequest {int32 id = 1; / / Unique ID number for a User. String name = 2; string email = 3; string phone= 4; message Address {string province = 1; string city = 2;} repeated Address addresses = 5;} message UserResponse {int32 id = 1; bool success = 2;} message UserFilter {int32 id = 1;}

Compile the .proto file

Protoc-go_out=plugins=grpc:. Userrpc.proto create new server server.gopackage mainimport ("log"net"golang.org/x/net/context"google.golang.org/grpc" pb "userrpc/grpc/user") const (port = ": 50051") / / server is used to implement user.UserServer.type server struct {savedUsers [] * pb.UserRequest} / / CreateUser creates a new Userfunc (s * server) CreateUser (ctx context.Context, in * pb.UserRequest) (* pb.UserResponse) Error) {s.savedUsers = append (s.savedUsers, in) return & pb.UserResponse {Id: in.Id, Success: true}, nil} / / GetUsers returns all users by given idfunc (s * server) GetUsers (filter * pb.UserFilter, stream pb.User_GetUsersServer) error {for _, user: = range s.savedUsers {if filter.Id = = 0 {continue} if err: = stream.Send (user) Err! = nil {return err}} return nil} func main () {lis, err: = net.Listen ("tcp", port) if err! = nil {log.Fatalf ("failed to listen:% v", err)} / / Creates a new gRPC server s: = grpc.NewServer () pb.RegisterUserServer (s, & server {}) s.Serve (lis)}

Client client.go

Package mainimport ("io"log"golang.org/x/net/context"google.golang.org/grpc" pb "userrpc/grpc/user") const (address = "localhost:50051") / / createUser calls the RPC method CreateUser of UserServerfunc createUser (client pb.UserClient, user * pb.UserRequest) {resp, err: = client.CreateUser (context.Background (), user) if err! = nil {log.Fatalf ("Could not createUser:% v") Err)} if resp.Success {log.Printf ("A new User has been added with id:% d", resp.Id)}} / / getUsers calls the RPC method GetUsers of UserServerfunc getUsers (client pb.UserClient, id * pb.UserFilter) {/ / calling the streaming API stream, err: = client.GetUsers (context.Background (), id) if err! = nil {log.Fatalf ("Error on get users:% v") Err)} for {user, err: = stream.Recv () if err = = io.EOF {break} if err! = nil {log.Fatalf ("% v.GetUsers (_) = _,% v", client, err)} log.Printf ("User:% v", user)} func main () {/ / Set up a connection to the gRPC server. Conn, err: = grpc.Dial (address, grpc.WithInsecure ()) if err! = nil {log.Fatalf ("did not connect:% v", err)} defer conn.Close () / / Creates a new UserClient client: = pb.NewUserClient (conn) user: = & pb.UserRequest {Id: 1, Name: "test", Email: "fasd@163.com", Phone: "132222222" Addresses: [] * pb.UserRequest_Address {& pb.UserRequest_Address {Province: "hebei", City: "shijiazhuang",} / Create a new user createUser (client, user) / / Filter with an id filter: = & pb.UserFilter {Id: 1} getUsers (client, filter)}

Start server.go

Go run server.go

Open a new window and start client.go

Go run client.go

The result is

17:01:16 on 2019-07-04 A new User has been added with id: 12019 shock 07 Accord 04 17:01:16 User: id:1 name: "test" >

The implementation of Api is tedious and brings difficulty to the development. Generally speaking, gRPC is a good cross-language rpc solution, and of course everyone has their own opinion or opinion. Adopting different solutions for different business scenarios is ultimately the result of the compromise between operational efficiency and development efficiency.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report