grpc

 (1)

配置多服务器只需要多几个不同地址的address就可以实现,如下图里。

下面的客户端也属于后端,并不是前端。下面的客户端像是一个中间层,前面是前段请求,后面不同服务,起服务派发效果。

(2)

跨主机服务的连接是通过各主机的下面代码中的被导入的pd包,加上下下面的用此pd来启动server来实现的

 

 


目录

(一)描述

grpc概述

grpc使用的协议缓冲protocol buffers

 

(二)实例

开发环境准备

定义服务

生成客户端和服务端代码

服务端实现

客户端实现


(一)描述

grpc概述

在gRPC里,客户端可以直接调用不同机器上的服务应用的方法,就像是本地对象一样,所以创建分布式应用和服务就很简单了。gRPC是基于定义一个服务,指定一个可以远程调用的带有参数和返回类型的的方法。在服务端,服务实现这个接口并且运行gRPC服务处理客户端调用。在客户端,有一个stub提供和服务端相同的方法。

 

在各种环境里,gRPC客户端和服务端都能运行并且互相通讯 - 从谷歌内部服务到你自己的桌面 - 并且可以写在任何gRPC支持的语言。比如,可以简单的创建java作为gRPC的服务端,Go,Python或者Ruby作为客户端。

grpc使用的协议缓冲protocol buffers

默认gRPC使用protocol buffers,Google成熟开源的序列化结构数据(尽管可以使用其他数据格式,比如JSON)。

使用协议缓冲的第一步是在proto file里为数据定义你想序列化的结构:可以是普通的.proto扩展的文本文件。协议缓冲数据结构为messages,每条message是一个小的逻辑记录的信息包含一些name-value对名为fields。比如:

message Person {
  string name = 1;
  int32 id = 2;
  bool has_ponycopter = 3;
}

然后,一旦你指定了你的数据结构,使用协议缓冲解析器protoc生成数据访问类在proto定义的语言。这些为每个字段(比如name()set_name())和方法序列化/解析整个结构到/从raw bytes提供了简单的访问器。

你将会在示例里看到更详细的定义在普通proto文件里的gRPC services,有RPC方法参数和指定的返回类型作为协议缓冲messages:

// The greeter 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;
}

gRPC同样使用protoc和指定的gRPC插件从你的proto文件里生成代码。但是,使用gRPC插件,你会得到生成的gRPC客户端和服务端代码和普通的用来populating,序列化和获取你的消息类型protocol buffer代码。

虽然protocal buffers有些时候对开源用户可用,我们的示例使用了新风格的protocal buffers,叫做proto3。

 

(二)实例

开发环境准备

工欲善其事必先利其器,在构建Go微服务前准备好开发环境可以提供工作效率和工作的舒心度。

  • Go
    gRPC要求Go语言的版本不低于1.6,建议使用最新稳定版本。如果没有安装Go或Go的版本低于1.6,参考Go安装指南

    $ go version 
    
  • 安装gRPC
    可以使用如下命令安装gRCP:

    $ go get -u google.golang.org/grpc
    

    如果网络质量不佳,可以直接去GitHub下载gRPC源码,将源码拷贝到$GOPATH路径下。

  • 安装 Protocol Buffers v3
    安装protoc编译器的目的是生成服务代码,从https://github.com/google/protobuf/releases下载已预编译好的二进制文件是安装protoc最简单的方法。
    1.1 解压文件
    1.2 将二进制文件所在的目录添加到环境变量PATH中。

    安装Go版本的protoc插件

    $ go get -u github.com/golang/protobuf/protoc-gen-go
    

    默认编译插件protoc-gen-to安装在$GOPATH/bin目录下,该目录需要添加到环境变量PATH中。

定义服务

在本文中定义一个产品服务ProductService,服务提供两个简单的基本功能

  • 添加产品
  • 删除产品
  • 根据产品Id查询产品详情
  • 查询所有产品详情
    ProductService.poto文件的具体内容如下:
// protocol buffer 语法版本
syntax = "proto3";

// 产品服务定义
service ProductService {
    // 添加产品
    rpc AddProduct (AddProductRequest) returns (AddProductResponse) {
    }

    // 删除产品
    rpc DeleteProduct (DeleteProductRequest) returns (EmptyResponse) {
    }

    // 根据产品Id查询产品详情
    rpc QueryProductInfo (QueryProductRequest) returns (ProductInfoResponse) {

    }

    // 查询所有产品详情
    rpc QueryProductsInfo (EmptyRequest) returns (ProductsInfoResponse) {

    }
}
// 请求/响应结构体定义
// 添加产品message
message AddProductRequest {
    enum Classfication {
        FRUIT = 0;
        MEAT = 1;
        STAPLE = 2;
        TOILETRIES = 3;
        DRESS = 4;
    }
    string productName = 1;
    Classfication classification = 2;
    string manufacturerId = 3;
    double weight = 4;
    int64 productionDate = 5;
}

// 添加产品,服务端响应message
message AddProductResponse {
    string productId = 1;
    string message = 2;
}

// 删除产品message
message DeleteProductRequest {
    string productId = 1;
}

message QueryProductRequest {
    string productId = 1;
}

// 单产品详情message
message ProductInfoResponse {
    string productName = 1;
    string productId = 2;
    string manufacturerId = 3;
    double weight = 4;
    int64 productionDate = 5;
    int64 importDate = 6;
}

message ProductsInfoResponse {
    repeated ProductInfoResponse infos = 1;
}

message EmptyRequest {

}

message EmptyResponse {

}

一个方法不需要入参或没有返回值时,在gRPC中使用空的message代替,参考stackoverflow

生成客户端和服务端代码

服务定义文件ProductService.poto在工程中的路径为:src/grpc/servicedef/product/ProductService.poto,进入servicedef目录,执行以下命令生成Go版本的客户端和服务端代码:

   $ protoc -I product/ ProductService.proto --go_out=plugins=grpc:product

命令执行完成后,会在product目录下生成一个名为ProductService.pb.go的文件,文件的内容为Go版本的客户端和服务端代码。

服务端实现

服务端需要完成两项工作才能对外提供RPC服务:

  • 实现ProductServiceServer接口,ProductServiceServer接口是protoc编译器自动生成。在Go某个对象实现一个接口,只需要实现该接口的所有方法。
  • 启动gRPC Server用来处理客户端请求。
    服务端具体实现代码
package main

import (
    "log"
    "net"
    "time"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"
    pb "grpc/servicedef/product"
    "math/rand"
    "strconv"
)

const (
    port = ":5230"
)

var dataBase = make(map[string]*Product, 10)

type Product struct {
    ProductName    string
    ProductId      string
    ManufacturerId string
    Weight         float64
    ProductionDate int64
    ImportDate     int64
}

type server struct{}

func (s *server) AddProduct(ctx context.Context, request *pb.AddProductRequest) (*pb.AddProductResponse, error) {
    log.Printf("get request from client to add product,request is %s", request)
    productId := strconv.FormatInt(rand.Int63(), 10)
    product :=new (Product)
    product.ProductName = request.ProductName
    product.ProductId = productId
    product.ManufacturerId = request.ManufacturerId
    product.Weight = request.Weight
    product.ProductionDate = request.ProductionDate
    product.ImportDate = time.Now().UnixNano()
    dataBase[productId] = product
    return &pb.AddProductResponse{ProductId: productId, Message: "Add product success"}, nil
}

func (s *server) DeleteProduct(ctx context.Context, request *pb.DeleteProductRequest) (*pb.EmptyResponse, error) {
    log.Printf("get request from client to add product,request is %s", request)
    productId := request.ProductId
    delete(dataBase, productId)
    return nil, nil
}

func (s *server) QueryProductInfo(ctx context.Context, request *pb.QueryProductRequest) (*pb.ProductInfoResponse, error) {
    log.Printf("get request from client fro query product info,%v", request)
    productId := request.ProductId
    product := dataBase[productId]
    response:=new(pb.ProductInfoResponse)
    response.ProductName = product.ProductName
    response.ProductId = product.ProductId
    response.ManufacturerId = product.ManufacturerId
    response.Weight = product.Weight
    response.ProductionDate = product.ProductionDate
    response.ImportDate = product.ImportDate
    return response, nil
}

func (s *server) QueryProductsInfo(ctx context.Context, request *pb.EmptyRequest) (*pb.ProductsInfoResponse, error) {
    // 待实现
    return nil, nil
}

func main() {
    log.Printf("begin to start rpc server")
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterProductServiceServer(s, &server{})
    // Register reflection service on gRPC server.
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

客户端实现

客户端非常的简单,就像gRPC介绍中一样,可以像调用本地方法一样调用远程gRPC服务,一个详细的例子如下:

package main

import (
    "log"
    "time"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    pb "grpc/servicedef/product"
)

const (
    address = "localhost:5230"
)

func main()  {
    // 建立一个与服务端的连接.
    conn, err := grpc.Dial(address, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    client := pb.NewProductServiceClient(conn)
    
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)

    response,err := client.AddProduct(ctx,&pb.AddProductRequest{ProductName:"phone"})
    if nil != err {
        log.Fatalf("add product failed, %v",err)
    }
    log.Printf("add product success,%s",response)
    productId:=response.ProductId
    queryResp,err :=client.QueryProductInfo(ctx,&pb.QueryProductRequest{ProductId: productId})
    if nil !=err {
        log.Fatalf("query product info failed,%v",err)
    }
    log.Printf("Product info is %v",queryResp)

    defer cancel()
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值