• grpc实战(1)简单实现helloworld


    1、创建项目grpc_demo文件架构,项目架构如下:

     2、在helloworld文件夹下创建hello_world.proto文件,内容如下:

    //声明proto的版本 只有 proto3 才支持 gRPC
    syntax = "proto3";
    // 将编译后文件输出在 github.com/lixd/grpc-go-example/helloworld/helloworld 目录
    option go_package = "github.com/lixd/grpc-go-example/helloworld/helloworld";
    // 指定当前proto文件属于helloworld包
    package helloworld;
    
    // 定义一个名叫 greeting 的服务
    service Greeter {
      // 该服务包含一个 SayHello 方法 HelloRequest、HelloReply分别为该方法的输入与输出
      rpc SayHello (HelloRequest) returns (HelloReply) {}
    }
    // 具体的参数定义
    message HelloRequest {
      string name = 1;
    }
    
    message HelloReply {
      string message = 1;
    }
    

    3、在helloworld目录下运行如下命令:

    protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative  ./hello_world.proto
    

      此时,helloworld文件下会出现后缀为pb.go和_grpc.pb.go的两个文件。

    4、编写server代码:

    具体步骤如下:

    • 1)定义一个结构体,必须包含pb.UnimplementedGreeterServer 对象;
    • 2)实现 .proto文件中定义的API;
    • 3)将服务描述及其具体实现注册到 gRPC 中;
    • 4)在server目录下分别运行命令go mod init server、go mod tidy;
    • 5)启动服务。
    package main
    
    import (
    	"context"
    	"log"
    	"net"
    
    	pb "github.com/lixd/grpc-go-example/helloworld/helloworld"
    	"google.golang.org/grpc"
    )
    
    const (
    	port = ":50051"
    )
    
    // greeterServer 定义一个结构体用于实现 .proto文件中定义的方法
    // 新版本 gRPC 要求必须嵌入 pb.UnimplementedGreeterServer 结构体
    type greeterServer struct {
    	pb.UnimplementedGreeterServer
    }
    
    // SayHello 简单实现一下.proto文件中定义的 SayHello 方法
    func (g *greeterServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    	log.Printf("Received: %v", in.GetName())
    	return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
    }
    
    func main() {
    	listen, err := net.Listen("tcp", port)
    	if err != nil {
    		log.Fatalf("failed to listen: %v", err)
    	}
    	s := grpc.NewServer()
    	// 将服务描述(server)及其具体实现(greeterServer)注册到 gRPC 中去.
    	// 内部使用的是一个 map 结构存储,类似 HTTP server。
    	pb.RegisterGreeterServer(s, &greeterServer{})
    	log.Println("Serving gRPC on 0.0.0.0" + port)
    	if err := s.Serve(listen); err != nil {
    		log.Fatalf("failed to serve: %v", err)
    	}
    }
    

    5、编写client代码:

    具体步骤如下:

    • 1)首先使用 grpc.Dial() 与 gRPC 服务器建立连接;
    • 2)使用pb.NewGreeterClient(conn)获取客户端;
    • 3)通过客户端调用ServiceAPI方法client.SayHello
    • 4)在client目录下分别运行命令go mod init client、go mod tidy;
    • 5)运行客户端。
    package main
    
    import (
    	"context"
    	"log"
    	"os"
    	"time"
    
    	pb "github.com/lixd/grpc-go-example/helloworld/helloworld"
    	"google.golang.org/grpc"
    )
    
    const (
    	address     = "localhost:50051"
    	defaultName = "world"
    )
    
    func main() {
    	conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
    	if err != nil {
    		log.Fatalf("did not connect: %v", err)
    	}
    	defer conn.Close()
    	c := pb.NewGreeterClient(conn)
    
    	// 通过命令行参数指定 name
    	name := defaultName
    	if len(os.Args) > 1 {
    		name = os.Args[1]
    	}
    	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    	defer cancel()
    	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
    	if err != nil {
    		log.Fatalf("could not greet: %v", err)
    	}
    	log.Printf("Greeting: %s", r.GetMessage())
    }
    

      

    参考:(29条消息) 史上最细gRPC(Go)入门教程(二)---gRPC初体验--hello world_指月小筑的博客-CSDN博客

  • 相关阅读:
    bzoj 2337 [HNOI2011]XOR和路径【高斯消元+dp】
    bzoj 3196 Tyvj 1730 二逼平衡树【线段树 套 splay】
    bzoj 3528 [Zjoi2014]星系调查【树链剖分+数学】
    bzoj 2127 happiness【最小割+dinic】
    bzoj 3110 [Zjoi2013]K大数查询【树套树||整体二分】
    bzoj 4137 [FJOI2015]火星商店问题【CDQ分治+可持久化trie】
    运用背景橡皮擦抠透明郁金香
    使用快速通道抠荷花
    抠图总结
    花纹的选区
  • 原文地址:https://www.cnblogs.com/mango1997/p/16218781.html
Copyright © 2020-2023  润新知