当前位置:网站首页>[grpc development] go language builds simple server and client
[grpc development] go language builds simple server and client
2022-06-12 05:32:00 【cbdgz】
gRPC Development :go Language to build simple server and client
preparation
- install protocol buffers
To protocol buffers To github To release Page download guide zip ( This article takes mac System installation protocol buffers For chestnuts , Other system method types )
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Kn4rD0UZ-1645623191826)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a1428a71-66cd-4049-85b3-61b3a51ad1d1/Untitled.png)]](/img/9a/665d2080471eba470c89b26952ed39.jpg)
After downloading, unzip and enter the unzipped directory
Directly execute the following commands in turn protocol buffers Installation1. ./configure 2. make 3. make check 4. sudo make install 5. protoc --version Test whether the installation is successful by checking the version![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-6hYhHUUs-1645623191835)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a2103e85-a87e-4bac-9e61-14de9c6e42e9/Untitled.png)]](/img/4c/172d98cc81a2a2d103b49d3d296d79.jpg)
Install the third party required for this article go library
go get -u google.golang.org/grpc # install gRPC library go get -u github.com/golang/protobuf/protoc-gen-go # install go Linguistic protoc plug-in unit
Start developing
Create a directory structure in the following format ( The structure of this article is not unique , Readers can find a better structure by themselves )
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-XccWfZes-1645623191836)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/6b4cbd89-8993-40de-a443-3b84716ced95/Untitled.png)]](/img/f7/7c9def6f0b93066f7b148b06e52a80.jpg)
among ecommerce Directory is used to store automatically generated stub files
Get into service The directory is created by executing the following command go Of productinfo/service modular
go mod init productinfo/serviceAfter successful execution, it will be in service Generate go.mod file
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BD5caNTq-1645623191838)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e81ed77f-0ce7-4e66-9358-8fc69d9136a2/Untitled.png)]](/img/fc/2b2624ffabe2de5e4c81f3aabcbb6f.jpg)
Defining services , stay ecommerce Create under directory product_info.proto And define the following services ( The service definitions of client and server are the same )
syntax = "proto3"; package ecommerce; option go_package = "../ecommerce"; service ProductInfo{ rpc addProduct(Product) returns (ProductID);// Define add product rpc getProduct(ProductID) returns(Product);// Define acquisition products , Only one parameter can be passed in and returned } // Define the product message body , The same message body cannot have the same number message Product { string id = 1; string name = 2; string description = 3; float price = 4 ; } // Define the product number message body message ProductID{ string value = 1; }stay service Execute the following command under the directory to generate the service definition code
protoc -I ecommerce ecommerce/product_info.proto --go_out=plugins=grpc:$PWD/ecommerce![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Wu1GdRNH-1645623191840)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/9c77e717-8a23-467c-80d9-562983eb3ff4/Untitled.png)]](/img/b0/7b586cdf0c823e7a6f4bf61db4b9ba.jpg)
The generated code is shown in the figure
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-6v5j0Kur-1645623191841)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/7f74faca-cfc1-42ce-9024-0d99ae392f88/Untitled.png)]](/img/bd/2f061776bc81222726acbd042ba1c0.jpg)
Development server
Server directory structure
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-TmwDwGrM-1645623191843)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ed647f5c-0853-4e34-a03f-02555f71992d/Untitled.png)]](/img/36/d533a49d6208d12e201228f4b75644.jpg)
a. Server side processing function
// service.go package main import ( "context" "github.com/gofrs/uuid" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" pb "productinfo/service/ecommerce" ) // Used to implement ecommerce/product_info Server for type server struct { productMap map[string]*pb.Product } /* Context Object contains some metadata , For example, the identification of the end-user authorization token and the deadline of the request , This metadata will persist throughout the life of the request */ // AddProduct Realization ecommerce.AddProduct Of AddProduct Method func (s *server) AddProduct(ctx context.Context, in *pb.Product) (*pb.ProductID, error) { out, err := uuid.NewV4() // To generate an item UID if err != nil { return nil, status.Errorf(codes.Internal, "Error while generating Product ID", err) } in.Id = out.String() // Initialize service , If the service is not initialized if s.productMap == nil { s.productMap = make(map[string]*pb.Product) } s.productMap[in.Id] = in return &pb.ProductID{ Value: in.Id}, status.New(codes.OK, "").Err() } // GetProduct Realization ecommerce.GetProduct Of GetProduct Method func (s *server) GetProduct(ctx context.Context, in *pb.ProductID) (*pb.Product, error) { value, exists := s.productMap[in.Value] if exists { return value, status.New(codes.OK, "").Err() } return nil, status.Errorf(codes.NotFound, "Product does not exits") }b. Server main function
// main.go package main import ( "google.golang.org/grpc" "log" "net" pb "productinfo/service/ecommerce" ) const ( port = ":50051" ) func main() { lis, err := net.Listen("tcp", port) // stay 50051 Create on port gRPC service if err != nil { log.Fatalf("failed to listen:%v", err) } s := grpc.NewServer() // Create a new gRPC example pb.RegisterProductInfoServer(s, &server{ }) // Register the generated service to the new gRPC On log.Printf("Starting gRPC listener on port:%s", port) // Start listening for incoming messages on the specified port if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve %v", err) } }Development client
Client directory structure![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-NSjLggUn-1645623191846)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/24d0be59-ebe9-4dd3-b5c6-1dc55f6a6a5f/Untitled.png)]](/img/0f/a0869e32afbd7c61af582e8498a4e4.jpg)
a. Client main function
//main.go package main import ( "context" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "log" pb "productinfo/client/ecommerce" "time" ) const ( address = "localhost:50051" ) func main() { conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials())) // Establish a link between the client and the server if err != nil { log.Fatalf("did not connect %v", err) } defer conn.Close() c := pb.NewProductInfoClient(conn) // Pass the connection and create a stub file . This instance contains all the remote methods that can call the server name := "MacBook Pro 2021" description := `Ultimate performance ( Ultimate performance )` price := float32(14000.0) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() // The remote invocation AddProduct Method r, err := c.AddProduct(ctx, &pb.Product{ Name: name, Description: description, Price: price}) if err != nil { log.Fatalf("Could not add Product:%v", err) } log.Printf("Product ID:%s added successfully", r.Value) // The remote invocation GetProduct Method product, err := c.GetProduct(ctx, &pb.ProductID{ Value: r.Value}) if err != nil { log.Fatalf("Could not get Product:%v", err) } log.Printf("Product: %v ", product.String()) }
Running results
Server side
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dqrLuTPM-1645623191848)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a9cc8b24-e0c9-4530-8772-1dbe3a815875/Untitled.png)]](/img/8a/40c4a134fa651b2e84075c1a48539c.jpg)
client
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-jHkFiVih-1645623191848)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/b122f2f4-706c-43ad-bfc1-b916794c8301/Untitled.png)]](/img/24/06c3c1219ecad7e117f4df152e9ce7.jpg)
边栏推荐
- Pupanvr create project and management script (2)
- MySQL5.7.21 Build For ARM
- Automated test - dark horse headline test project
- 论文阅读_图神经网络GIN
- 个体工商户是不是法人企业
- Variables and data types
- 关于架构(排名不分先后)
- How long is the company's registered capital subscribed
- Performance test - GTI application service performance monitoring platform
- Go interface oriented programming practice
猜你喜欢

Halcon 用点来拟合平面

Go 面向接口编程实战

Word frequency statistics using Jieba database

16. sum of the nearest three numbers

Detailed analysis of the 2021 central China Cup Title A (color selection of mosaic tiles)

Selenium crawler automatically captures TOEFL test position of NEEA website

什么是工程预付款

4.3 模拟浏览器操作和页面等待(显示等待和隐式等待、句柄)

Thesis reading_ Figure neural network gin

Matlab: halftone and dither conversion
随机推荐
分公司负责人需要承担的法律责任
C language - how to define arrays
Details of FPGA syntax
Sv806 QT UI development
深入理解异步编程
Halcon 3D 1 读取3d数据
12.26 exercise summary
Lldp protocol
Introduction to audio alsa architecture
Project requirements specification
Field xxxxDAO in com. nero. hua. service. impl. LoginServiceImpl required a bean of type
Object class not ended
What is thinking
The relation between virtual function and pure virtual function
51. reverse order pairs in the array
16. Somme des trois plus proches
Performance test - Analysis of performance test results
31. stack push in and pop-up sequence
Automated test - dark horse headline test project
Greenplum [question 05] Greenplum streaming server custom client problem handling (increasing)