说到rpc其实就是云计算中非常新的一种aas叫做faas,也就是function as a service的一种最佳实践,也就是把一套函数作为一种服务提供给开发者调用,现在最经常使用的比如之前的swapi就是很好的一种体现,通过远程调用函数来得到想要的结果,又比如说是百度地图等等地位导航的服务如果需要在自己的应用中使用,完全可以仅仅只需要调用所提供的函数既可,而不需要额外进行跳转等步骤。
但是有意思的是为什么我们真正需要rpc呢,这个和之前所使用的http中的graphql,restful究竟有什么区别呢。这还是需要细细得来分析,因为本质上其实grpc的实现更多程度上还是对于应用层协议的一种包装,是通过更方便的调用方式来实现的相应功能,同时还可以在传输的基础上加上各种我们所想要的安全措施。
这还只是其中的一小部分,当真正设计到要开发出一容错率足够强大的faas,那么就会面临数据序列化、反序列化、连接管理、收发线程、超时处理等问题。如果自己实现一套这样的机制,不但重复劳动,性能和效率也难以保证
这一次的实验就是使用go语言来实践这一个设计,
go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/protoc-gen-go
其由 Google 主要面向移动应用开发并基于HTTP/2 协议标准而设计,基于 ProtoBuf(Protocol Buffers) 序列化协议开发,且支持众多开发语言。本文作者深入研究了 gRPC 协议,对协议本身作出解构。
所以我们还需要额外安装protobuf这一个依赖项目。
可以查看样例所提供的官方实践
helloworld.proto
// 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.
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;
}
protoc编译器可以把它编译成一个相应的.pb.go文件。
$ protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
在服务器中运行对应grpc服务
go run greeter_server/main.go
通过用户端程序远程进行调用
go run greeter_client/main.go
2019/01/18 20:31:15 Greeting: Hello world
2019/01/18 20:31:15 Received: world
成功运行