gRPC学习之简单实现C\S通信(第三十八天)

总结

增加、修改一个grpc接口步骤:
1.修改proto文件,新增修改一个service,相应的请求和回复的message
2.使用protoc生成go代码
3.server和cilent分别调用生成的go包里的方法
这个也就是平台中立的体现,没有完全的平台中立,只是从新设计。

thrift和 grpc的优劣:

1.依据网络进行合理选择
2.thrift是Facebook的开源rpc框架,thrift的rpc,一次调用在收到回复之前,占用一个TCP连接的,当并发量很高,而一次调用耗时又很长的时候,thrift会出现连接被占满的情况,导致调用堆积,延时增大.
3.grpc是基于http-2设计的,http-2的一个重要特点是在单个TCP连接上可以复用多个请求.而grpc,多个调用可以复用一个连接,这样显然就比thrift支持的并发调用数量更高。

具体实现(照猫画虎)

  • 使用protoc生成 proto文件,类如grpc 提供的example中的helloworld
    执行protoc.exe ,发现这个编译器插件支持的大概命令
    以及版本,我的是libprotoc 3.6.1
$ protoc.exe
Usage: D:\GO\bin\protoc.exe [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
  -IPATH, --proto_path=PATH   Specify the directory in which to search for
                              imports.  May be specified multiple times;
                              directories will be searched in order.  If not
                              given, the current working directory is used.
  --version                   Show version info and exit.
  -h, --help                  Show this text and exit.
  --encode=MESSAGE_TYPE       Read a text-format message of the given type
                              from standard input and write it in binary
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.
  --decode=MESSAGE_TYPE       Read a binary message of the given type from
                              standard input and write it in text format
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.
  --decode_raw                Read an arbitrary protocol message from
                              standard input and write the raw tag/value
                              pairs in text format to standard output.  No
                              PROTO_FILES should be given when using this
                              flag.
  --descriptor_set_in=FILES   Specifies a delimited list of FILES
                              each containing a FileDescriptorSet (a
                              protocol buffer defined in descriptor.proto).
                              The FileDescriptor for each of the PROTO_FILES
                              provided will be loaded from these
                              FileDescriptorSets. If a FileDescriptor
                              appears multiple times, the first occurrence
                              will be used.
  -oFILE,                     Writes a FileDescriptorSet (a protocol buffer,
    --descriptor_set_out=FILE defined in descriptor.proto) containing all of
                              the input files to FILE.
  --include_imports           When using --descriptor_set_out, also include
                              all dependencies of the input files in the
                              set, so that the set is self-contained.
  --include_source_info       When using --descriptor_set_out, do not strip
                              SourceCodeInfo from the FileDescriptorProto.
                              This results in vastly larger descriptors that
                              include information about the original
                              location of each decl in the source file as
                              well as surrounding comments.
  --dependency_out=FILE       Write a dependency output file in the format
                              expected by make. This writes the transitive
                              set of input file paths to FILE
  --error_format=FORMAT       Set the format in which to print errors.
                              FORMAT may be 'gcc' (the default) or 'msvs'
                              (Microsoft Visual Studio format).
  --print_free_field_numbers  Print the free field numbers of the messages
                              defined in the given proto files. Groups share
                              the same field number space with the parent
                              message. Extension ranges are counted as
                              occupied fields numbers.

  --plugin=EXECUTABLE         Specifies a plugin executable to use.
                              Normally, protoc searches the PATH for
                              plugins, but you may specify additional
                              executables not in the path using this flag.
                              Additionally, EXECUTABLE may be of the form
                              NAME=PATH, in which case the given plugin name
                              is mapped to the given executable even if
                              the executable's own name differs.
  --cpp_out=OUT_DIR           Generate C++ header and source.
  --csharp_out=OUT_DIR        Generate C# source file.
  --java_out=OUT_DIR          Generate Java source file.
  --js_out=OUT_DIR            Generate JavaScript source.
  --objc_out=OUT_DIR          Generate Objective C header and source.
  --php_out=OUT_DIR           Generate PHP source file.
  --python_out=OUT_DIR        Generate Python source file.
  --ruby_out=OUT_DIR          Generate Ruby source file.
  @<filename>                 Read options and filenames from file. If a
                              relative file path is specified, the file
                              will be searched in the working directory.
                              The --proto_path option will not affect how
                              this argument file is searched. Content of
                              the file will be expanded in the position of
                              @<filename> as in the argument list. Note
                              that shell expansion is not applied to the
                              content of the file (i.e., you cannot use
                              quotes, wildcards, escapes, commands, etc.).
                              Each line corresponds to a single argument,
                              even if it contains spaces.

$ protoc.exe --version
libprotoc 3.6.1

  • 自带的列子中helloworld.proto 的内容:
syntax = "proto3";  

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";

package helloworld;     //包名

// The greeting service definition. 服务器调用的方法
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.//请求消息中的格式字段
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings//响应消息中的格式字段
message HelloReply {
  string message = 1;
}

解释如下:
syntax = “proto3” 指定proto版本
package helloworld protoc命令生成的go代码的包名,客户端服务器程序都要引用这个包,所在路径同名
service 定义了这个远程调用的服务,服务请求者调用SayHello方法,请求中携带HelloRequest格式的信息,服务提供者则返回HelloReply格式的回复
message 这个就是定义请求和回复的格式

  • 生成对应的go语言代码,这里终于要用到我们最开始安装的protoc了,命令如下:
protoc.exe --go_out=plugins=grpc:. helloworld.proto
liu@liu-PC MINGW64 /d/GO/GO_WORKSPACE/src/google.golang.org/grpc/examples/helloworld/helloworld (master)
$ ls
helloworld.pb.go  helloworld.proto

liu@liu-PC MINGW64 /d/GO/GO_WORKSPACE/src/google.golang.org/grpc/examples/helloworld/helloworld (master)
$

liu@liu-PC MINGW64 /d/GO/GO_WORKSPACE/src/google.golang.org/grpc/examples/helloworld/helloworld (master)
$ rm helloworld.pb.go

liu@liu-PC MINGW64 /d/GO/GO_WORKSPACE/src/google.golang.org/grpc/examples/helloworld/helloworld (master)
$ ls
helloworld.proto

liu@liu-PC MINGW64 /d/GO/GO_WORKSPACE/src/google.golang.org/grpc/examples/helloworld/helloworld (master)
$ protoc.exe --go_out=plugins=grpc:. helloworld.proto
2020/04/18 22:17:11 WARNING: Missing 'go_package' option in "helloworld.proto", please specify:
        option go_package = ".;helloworld";
A future release of protoc-gen-go will require this be specified.
See https://developers.google.com/protocol-buffers/docs/reference/go-generated#package for more information.
liu@liu-PC MINGW64 /d/GO/GO_WORKSPACE/src/google.golang.org/grpc/examples/helloworld/helloworld (master)
$ ls
helloworld.pb.go  helloworld.proto

  • 编写服务器、客户端的代码,记得 import pb"google.golang.org/grpc/examples/helloworld/helloworld"
    “google.golang.org/grpc”
    “context”

客户端代码:


package main

import (
	"context"
	"log"
	"os"
	"time"
	"google.golang.org/grpc"                                       //grpc 的包
	pb "google.golang.org/grpc/examples/helloworld/helloworld"     //生产的中间文件
)

const (
	address     = "localhost:50051"      //ip + port
	defaultName = "world"              
)

func main() {
	// Set up a connection to the server.
	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)

	// Contact the server and print out its response.
	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())
}

服务器代码:

/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

//go:generate protoc -I ../helloworld --go_out=plugins=grpc:../helloworld ../helloworld/helloworld.proto

// Package main implements a server for Greeter service.
package main

import (
	"context"
	"log"
	"net"

	"google.golang.org/grpc"
	pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
	port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
type server struct {
	pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) 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() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

运行结果:

客户端:2020/04/18 22:37:57 Received: world

服务端:2020/04/18 22:37:57 Received: world

发布了205 篇原创文章 · 获赞 47 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/qq_32744005/article/details/105606383