Grpc系列学习(二)

Grpc系列学习(二)

写在前面:因为1024CSDN写博客会有徽章,本人多少带点收集控,故正好整理出第二篇关于Grpc的学习文章.

这次照例宣传一下我的个人博客:

demo:

制作证书

在服务端支持RpcRestful Api,需要用到TLS,因此我们要先制作证书

进入certs目录,生成TLS所需的公钥密钥文件

openssl genrsa -out server.key 2048

openssl ecparam -genkey -name secp384r1 -out server.key
  • openssl genrsa:生成RSA私钥,命令的最后一个参数,将指定生成密钥的位数,如果没有指定,默认512
  • openssl ecparam:生成ECC私钥,命令为椭圆曲线密钥参数生成及操作,本文中ECC曲线选择的是secp384r1
自签名公钥
openssl req -new -x509 -sha256 -key server.key -out server.pem -days 3650

openssl req:生成自签名证书,-new指生成证书请求、-sha256指使用sha256加密、-key指定私钥文件、-x509指输出证书、-days 3650为有效期,此后则输入证书拥有者信息

填写信息
Country Name (2 letter code) [XX]:
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:grpc server name
Email Address []:

Proto

编写

1.google.api

我们看到proto目录中有google/api目录,它用到了google官方提供的两个api描述文件,主要是针对grpc-gatewayhttp转换提供支持,定义了Protocol Buffer所扩展的HTTP Option

annotations.proto文件:

// Copyright (c) 2015, Google Inc.
//
// 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.
​
syntax = "proto3";
​
package google.api;
​
import "google/api/http.proto";
import "google/protobuf/descriptor.proto";
​
option java_multiple_files = true;
option java_outer_classname = "AnnotationsProto";
option java_package = "com.google.api";
​
extend google.protobuf.MethodOptions {
  // See `HttpRule`.
  HttpRule http = 72295728;
}

http.proto文件:

// Copyright 2016 Google Inc.
//
// 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.

syntax = "proto3";

package google.api;

option cc_enable_arenas = true;
option java_multiple_files = true;
option java_outer_classname = "HttpProto";
option java_package = "com.google.api";


// Defines the HTTP configuration for a service. It contains a list of
// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
// to one or more HTTP REST API methods.
message Http {
  // A list of HTTP rules for configuring the HTTP REST API methods.
  repeated HttpRule rules = 1;
}

// Use CustomHttpPattern to specify any HTTP method that is not included in the
// `pattern` field, such as HEAD, or "*" to leave the HTTP method unspecified for
// a given URL path rule. The wild-card rule is useful for services that provide
// content to Web (HTML) clients.
message HttpRule {
  // Selects methods to which this rule applies.
  //
  // Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
  string selector = 1;

  // Determines the URL pattern is matched by this rules. This pattern can be
  // used with any of the {get|put|post|delete|patch} methods. A custom method
  // can be defined using the 'custom' field.
  oneof pattern {
    // Used for listing and getting information about resources.
    string get = 2;

    // Used for updating a resource.
    string put = 3;

    // Used for creating a resource.
    string post = 4;

    // Used for deleting a resource.
    string delete = 5;

    // Used for updating a resource.
    string patch = 6;

    // Custom pattern is used for defining custom verbs.
    CustomHttpPattern custom = 8;
  }

  // The name of the request field whose value is mapped to the HTTP body, or
  // `*` for mapping all fields not captured by the path pattern to the HTTP
  // body. NOTE: the referred field must not be a repeated field.
  string body = 7;

  // Additional HTTP bindings for the selector. Nested bindings must
  // not contain an `additional_bindings` field themselves (that is,
  // the nesting may only be one level deep).
  repeated HttpRule additional_bindings = 11;
}

// A custom pattern is used for defining custom HTTP verb.
message CustomHttpPattern {
  // The name of this custom HTTP verb.
  string kind = 1;

  // The path matched by this custom verb.
  string path = 2;
}
  1. hello.proto

这一小节将编写Demo.proto文件,我们在proto目录下新建hello.proto文件,写入文件内容:

syntax = "proto3";

package proto;

import "google/api/annotations.proto";

service HelloWorld {
    rpc SayHelloWorld(HelloWorldRequest) returns (HelloWorldResponse) {
        option (google.api.http) = {
            post: "/hello_world"
            body: "*"
        };
    }
}

message HelloWorldRequest {
    string referer = 1;
}

message HelloWorldResponse {
    string message = 1;
}

hello.proto文件中,引用了google/api/annotations.proto,达到支持HTTP Option的效果

  • 定义了一个serviceRPC服务HelloWorld,在其内部定义了一个HTTP OptionPOST方法,HTTP响应路径为/hello_world
  • 定义message类型HelloWorldRequestHelloWorldResponse,用于响应请求和返回结果

编译

在编写完.proto文件后,我们需要对其进行编译,就能够在server中使用

进入proto目录,执行以下命令

# 编译google.api
protoc -I . --go_out=plugins=grpc,Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor:. google/api/*.proto

#编译hello_http.proto为hello_http.pb.proto
protoc -I . --go_out=plugins=grpc,Mgoogle/api/annotations.proto=grpc-hello-world/proto/google/api:. ./hello.proto

#编译hello_http.proto为hello_http.pb.gw.proto
protoc --grpc-gateway_out=logtostderr=true:. ./hello.proto

执行完毕后将生成hello.pb.gohello.gw.pb.go,分别针对grpcgrpc-gateway的功能支持

命令行模块 cmd

介绍

这一小节我们编写命令行模块,为什么要独立出来呢,是为了将cmdserver两者解耦,避免混淆在一起。

我们采用 Cobra 来完成这项功能,Cobra既是创建强大的现代CLI应用程序的库,也是生成应用程序和命令文件的程序。提供了以下功能:

  • 简易的子命令行模式
  • 完全兼容posix的命令行模式(包括短和长版本)
  • 嵌套的子命令
  • 全局、本地和级联flags
  • 使用Cobra很容易的生成应用程序和命令,使用cobra create appnamecobra add cmdname
  • 智能提示
  • 自动生成commands和flags的帮助信息
  • 自动生成详细的help信息-h--help等等
  • 自动生成的bash自动完成功能
  • 为应用程序自动生成手册
  • 命令别名
  • 定义您自己的帮助、用法等的灵活性。
  • 可选与viper紧密集成的apps

—选自某百科

编写server

在编写cmd时需要先用server进行测试关联,因此这一步我们先写server.go用于测试

server模块下 新建server.go文件,写入测试内容:

package server

import (
    "log"
)

var (
    ServerPort string
    CertName string
    CertPemPath string
    CertKeyPath string
)

func Serve() (err error){
    log.Println(ServerPort)

    log.Println(CertName)

    log.Println(CertPemPath)

    log.Println(CertKeyPath)

    return nil
}

编写cmd

cmd模块下 新建root.go文件,写入内容:

package cmd

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:   "grpc",
    Short: "Run the gRPC hello-world server",
}

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }
}

emmm…这个官网的Hello World还是有点多的,今天就不写了~~

@copyright ------------baijianruoliorz@Github--------------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: gRPC C是一个用C语言实现的开源高性能远程过程调用(RPC)框架。它基于Google的Protocol Buffers(protobuf)和HTTP/2协议,可以用于构建分布式系统中的服务器和客户端。下面以300字中文回答gRPC C的例子和优势: gRPC C的例子包括服务器和客户端的实现。在服务器方面,我们可以使用gRPC C来编写一个简单的服务器应用程序,它提供一些远程方法供客户端调用。我们可以定义一组方法和消息类型,在gRPC C中使用protobuf来序列化和反序列化这些消息,然后基于这些方法编写服务器端逻辑。客户端可以使用gRPC C的API来调用服务器上的方法,并获得返回结果。 gRPC C的优势主要体现在以下几个方面: 1. 高性能:gRPC C基于HTTP/2协议,通过多路复用和流水线技术实现了高效的并发通信。这使得gRPC C在网络传输效率和性能方面表现出色,能够处理大量请求和响应。 2. 跨平台支持:gRPC C可以在各种操作系统上运行,包括Linux、Windows和MacOS等。这使得开发者可以在不同的平台上使用相同的代码和API来构建分布式系统。 3. 强大的工具支持:gRPC C提供了丰富的工具来帮助开发者构建和测试gRPC应用。例如,它提供了自动生成代码的工具,可以根据protobuf文件自动创建服务器和客户端的代码。此外,gRPC C还提供了CLI工具,用于测试和调试gRPC应用。 4. 扩展性和可靠性:gRPC C支持多种负载均衡模式和错误处理机制,可以根据具体的需求进行配置。这使得gRPC C在构建大规模分布式系统时具有良好的可扩展性和可靠性。 总之,gRPC C是一个功能强大且性能优越的远程过程调用框架,可以帮助开发者快速构建高效的分布式系统。它提供了丰富的工具和跨平台支持,使得开发和部署变得更加简单和可靠。 ### 回答2: gRPC C是一个用于构建高性能、跨平台的分布式系统的开源框架。它基于Google开发的gRPC协议,使用了Protocol Buffers作为默认的序列化机制。gRPC C提供了一系列功能强大的API,可以让开发者轻松地构建可扩展的分布式应用程序。 在gRPC C中,我们可以使用例子来更好地理解和学习框架的使用方式。gRPC C提供了一些示例代码,可作为开发者的起点和参考。这些示例覆盖了不同功能和用例,帮助开发者快速上手和理解具体的用法。 这些例子包括但不限于以下几个方面: 1. HelloWorld:这是最简单的示例,展示了如何使用gRPC C来实现一个基本的客户端-服务器通信。它涉及到建立服务器和客户端的连接,发送和接收简单的消息。 2. RouteGuide:这个示例演示了如何使用gRPC C构建一个简单的位置服务应用程序。它通过gRPC C的API实现了一些常见操作,如新建、添加、查询位置等。 3. Chat:这个示例展示了如何利用gRPC C实现一个简单的聊天应用程序。它使用gRPC C的流式处理能力,支持多个客户端同时与服务器进行通信,实现实时消息的广播和接收。 通过运行和分析这些示例,开发者可以学习到gRPC C的各种功能和用法。这些示例提供了一个实践的方式,让开发者能够更好地理解和掌握gRPC C框架。开发者可以根据自身需求和具体场景,参考这些示例并进行相应的修改和定制。 ### 回答3: gRPC C是一个基于C语言的远程过程调用(RPC)框架,它可以让不同的应用程序在网络上相互通信。提供了跨越不同语言和平台的高效通信机制。 gRPC C的例子主要是用来演示如何在C语言中使用gRPC进行远程过程调用。这些例子通常包括一个服务器端和一个或多个客户端。通过这些例子,我们可以了解gRPC的基本概念和使用方法。 在gRPC C的例子中,通常会涉及到定义服务的接口文件、使用协议缓冲区(Protocol Buffers)来定义消息的结构和传输格式,以及实现服务器端和客户端的具体逻辑。通过这些例子,我们可以学习如何在C语言中使用gRPC构建分布式系统。 这些例子可以帮助我们理解gRPC的工作原理,并实现简单的分布式应用程序。通过这些例子,我们可以学习到如何定义服务接口、处理请求和响应、处理错误和异常等。 总而言之,gRPC C的例子是帮助我们在C语言中学习和使用gRPC的有效工具。它们提供了一个实用的指南,让我们能够快速入门并开始构建分布式应用程序。通过这些例子,我们可以更深入地了解gRPC的特性和优势,并在实际项目中应用它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值