问题提出:
有两个服务A和B,A和B分别部署在不同的服务器上,A要调用B服务的求和函数sumfunc,如何实现?
RPC远程过程调用(Remote Procedure Call),一种用来处理远程机器之前通信问题的一种解决方案,RPC的出发点是屏蔽掉网络协议层的繁琐协议,能给用户暴露最直接的远程调用API。简单的理解是一个节点请求另一个节点提供的服务。
要具体的理解RPC,我们先了解“过程”概念:
1)同一个进程,同一个线程内部函数调用
此为常见的函数调用,一个线程内部函数嵌套的使用。根据操作系统的基本知识,编译器编译的过程中会将函数调用处给出函数执行的入口地址,通过该地址,在线程的地址空间找到对应要调用执行的函数。本质上为本地调用。
2)不同进程之间的函数调用
不同进程之间的函数调用实际是不同进程之间的通信问题,即IPC。
IPC通信有很多种方法,比较常见的是管道、共享内存、消息队列等。本质上函数的调用依然是本地调用,因为它们的访问还是同一个机器,在同一个内存访问空间上。
3)不同机器上跨网络的函数调用
此种方式也称为远程调用。传统的使用远程调用都是使用socket,用户自己编写socket,然后客户端和服务端遵循某种数据流协议,进行通信,完成函数的功能调用。
RPC从某种意义上来说,也是这样的,这种远程的调用,显然会增加大量的代码开发中的工作量,因为一个函数调用的功能,需要做网络协议,数据序列化这些逻辑,开发难度不断提升。
RPC采用客户机/服务器模式。请求程序就是一个客户机,而服务提供程序就是一个服务器。
RPC核心功能由5个部分组成:客户端、客户端Stub、网络传输模块、服务端Stud、服务端等。
本地调用中,函数体是直接通过函数指针来指定的,但是在远程调用中,函数指针是不行的,因为两个进程的地址空间是完全不一样的。这时,服务寻址可以使用 Call ID 映射,客户端和服务端分别维护一个函数和Call ID的对应表(所有的函数都必须有自己的一个 ID) 。
客户端在做远程过程调用时, 必须附上这个 ID。 当客户端需要进行远程调用时, 它就查一下这个表, 找出相应的 Call ID, 然后把它传给服务端,服务端也通过查表, 来确定客户端需要调用的函数, 然后执行相应函数的代码。
以客户端调用服务端addAge函数为例,过程如下:
// Client端
// Student student = Call(ServerAddr, addAge, student)
1. 将这个调用映射为Call ID。
2. 将Call ID,student(params)序列化,以二进制形式打包
3. 把2中得到的数据包发送给ServerAddr,这需要使用网络传输层
4. 等待服务器返回结果
5. 如果服务器调用成功,那么就将结果反序列化,并赋给student,年龄更新
// Server端
1. 在本地维护一个Call ID到函数指针的映射call_id_map,可以用Map<String, Method> callIdMap
2. 等待客户端请求
3. 得到一个请求后,将其数据包反序列化,得到Call ID
4. 通过在callIdMap中查找,得到相应的函数指针
5. 将student(params)反序列化后,在本地调用addAge()函数,得到结果
6. 将student结果序列化后通过网络返回给Client
1)基于TCP协议实现的RPC
TCP协议处于协议栈的下层,能够更加灵活地对协议字段进行定制,减少网络开销,提高性能,实现更大的吞吐量和并发数。
2)基于HTTP协议实现的RPC
可以使用JSON和XML格式的请求或响应数据。HTTP协议是上层协议,发送包含同等内容的消息,使用HTTP协议传输所占用的字节数会比使用TCP协议传输所占用的字节数更高。
RPC和Restful不是一个维度的概念,RPC涉及的维度更广。
1)从RPC风格的url和Restful风格的url比较
RPC url:/queryOrder?orderId=123
Restful url:Get /order?orderId=123
2)RPC是面向过程,Restful是面向资源
Restful风格的url在表述的精简性、可读性上都要更好。
Restful大部分是对外提供公共服务(Android、IOS客户端),更加容易理解,方便对外提供服务。
RPC更多的用于内部服务之间的调用。
1)gRPC
gRPC 是 Google 公布的开源软件, 基于谷歌的 HTTP 2.0 协议,并支持常见的众多编程语言。 RPC框架是基于HTTP协议实现的。
2)Thrift
Thrift 是 Facebook 的开源 RPC 框架,主要是一个跨语言的服务开发框架。用户只要在其之上进行二次开发就行,应用对于底层的 RPC 通讯等都是透明的。不过这个对于用户来说需要学习特定领域语言这个特性,还是有一定成本的。
3)Dubbo
Dubbo 是阿里集团开源的一个极为出名的 RPC 框架,在很多互联网公司和企业应用中广泛使用。协议和序列化框架都可以插拔是极其鲜明的特色。
4)BRPC
BRPC 是百度开源的PRC框架, “brpc”的含义是“better RPC”,已在百度有上百万实例的应用, C++语言实现,非常适合C/C++程序员学习。
编译步骤参考:https://github.com/apache/incubator-brpc/blob/master/docs/cn/getting_started.md
需要注意的是,protobuf依赖库的版本,目前不支持protobuf3.0。
(一)命令安装依赖包
BRPC需要依赖三个开源库:是gflags,protobuf和leveldb。
安装通用deps, gflags, protobuf, leveldb
sudo apt-get install -y git g++ make libssl-dev libgflags-dev libprotobuf-dev libprotoc-dev protobuf-compiler libleveldb-dev
如果需要leveldb
sudo apt-get install -y libsnappy-dev
(二)源码安装依赖包
源码安装的时候将路径设置为:--prefix=/usr
源码安装glog
$ git clone https://github.com/boboxxd/glog.git
$ cd glog
$ ./autogen.sh && ./configure --prefix=/usr && make && sudo make install
(三)编译BRPC
$ git clone https://gitee.com/baidu/BRPC.git
$ cd BRPC
$ sh config_brpc.sh --headers=/usr/include --libs=/usr/lib --with-glog
$ make
选项
--with-glog
。--nodebugsymbols
。--with-thrift
,并先安装thrift 。
百度给出了很多的案例,在git上,可以直接使用,我们这里使用最简单的读写例子。
$ cd example/echo_c++
$ make
$ ./echo_server &
$ ./echo_client
这里编译出来的是静态链接,如果想使用动态连接,先make clean
然后再LINK_SO=1 make
,生成动态链接的执行文件。
1)服务端源码
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
// A server to receive EchoRequest and send back EchoResponse.
#include
#include
#include
#include "echo.pb.h"
DEFINE_bool(echo_attachment, true, "Echo attachment as well");
DEFINE_int32(port, 8000, "TCP Port of this server");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no "
"read/write operations during the last `idle_timeout_s'");
DEFINE_int32(logoff_ms, 2000, "Maximum duration of server's LOGOFF state "
"(waiting for client to close connection before server stops)");
// Your implementation of example::EchoService
// Notice that implementing brpc::Describable grants the ability to put
// additional information in /status.
namespace example {
class EchoServiceImpl : public EchoService {
public:
EchoServiceImpl() {
};
virtual ~EchoServiceImpl() {
};
virtual void Echo(google::protobuf::RpcController* cntl_base,
const EchoRequest* request,
EchoResponse* response,
google::protobuf::Closure* done) {
// This object helps you to call done->Run() in RAII style. If you need
// to process the request asynchronously, pass done_guard.release().
brpc::ClosureGuard done_guard(done);
brpc::Controller* cntl =
static_cast<brpc::Controller*>(cntl_base);
// The purpose of following logs is to help you to understand
// how clients interact with servers more intuitively. You should
// remove these logs in performance-sensitive servers.
LOG(INFO) << "Received request[log_id=" << cntl->log_id()
<< "] from " << cntl->remote_side()
<< " to " << cntl->local_side()
<< ": " << request->message()
<< " (attached=" << cntl->request_attachment() << ")";
// Fill response.
response->set_message(request->message());
// You can compress the response by setting Controller, but be aware
// that compression may be costly, evaluate before turning on.
// cntl->set_response_compress_type(brpc::COMPRESS_TYPE_GZIP);
if (FLAGS_echo_attachment) {
// Set attachment which is wired to network directly instead of
// being serialized into protobuf messages.
cntl->response_attachment().append(cntl->request_attachment());
}
}
};
} // namespace example
int main(int argc, char* argv[])
{
// Parse gflags. We recommend you to use gflags as well.
GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
// Generally you only need one Server.
brpc::Server server;
// Instance of your service.
example::EchoServiceImpl echo_service_impl;
// Add the service into server. Notice the second parameter, because the
// service is put on stack, we don't want server to delete it, otherwise
// use brpc::SERVER_OWNS_SERVICE.
if (server.AddService(&echo_service_impl,
brpc::SERVER_DOESNT_OWN_SERVICE) != 0) {
LOG(ERROR) << "Fail to add service";
return -1;
}
// Start the server.
brpc::ServerOptions options;
options.idle_timeout_sec = FLAGS_idle_timeout_s;
if (server.Start(FLAGS_port, &options) != 0) {
LOG(ERROR) << "Fail to start EchoServer";
return -1;
}
// Wait until Ctrl-C is pressed, then Stop() and Join() the server.
server.RunUntilAskedToQuit();
return 0;
}
2)客户端源码
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
// A client sending requests to server every 1 second.
#include
#include
#include
#include
#include "echo.pb.h"
DEFINE_string(attachment, "", "Carry this along with requests");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "0.0.0.0:8000", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)");
DEFINE_int32(interval_ms, 1000, "Milliseconds between consecutive requests");
int main(int argc, char* argv[]) {
// Parse gflags. We recommend you to use gflags as well.
GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
// A Channel represents a communication line to a Server. Notice that
// Channel is thread-safe and can be shared by all threads in your program.
brpc::Channel channel;
// Initialize the channel, NULL means using default options.
brpc::ChannelOptions options;
options.protocol = FLAGS_protocol;
options.connection_type = FLAGS_connection_type;
options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
options.max_retry = FLAGS_max_retry;
if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {
LOG(ERROR) << "Fail to initialize channel";
return -1;
}
// Normally, you should not call a Channel directly, but instead construct
// a stub Service wrapping it. stub can be shared by all threads as well.
example::EchoService_Stub stub(&channel);
// Send a request and wait for the response every 1 second.
int log_id = 0;
while (!brpc::IsAskedToQuit()) {
// We will receive response synchronously, safe to put variables
// on stack.
example::EchoRequest request;
example::EchoResponse response;
brpc::Controller cntl;
request.set_message("hello world");
cntl.set_log_id(log_id ++); // set by user
// Set attachment which is wired to network directly instead of
// being serialized into protobuf messages.
cntl.request_attachment().append(FLAGS_attachment);
// Because `done'(last parameter) is NULL, this function waits until
// the response comes back or error occurs(including timedout).
stub.Echo(&cntl, &request, &response, NULL);
if (!cntl.Failed()) {
LOG(INFO) << "Received response from " << cntl.remote_side()
<< " to " << cntl.local_side()
<< ": " << response.message() << " (attached="
<< cntl.response_attachment() << ")"
<< " latency=" << cntl.latency_us() << "us";
} else {
LOG(WARNING) << cntl.ErrorText();
}
usleep(FLAGS_interval_ms * 1000L);
}
LOG(INFO) << "EchoClient is going to quit";
return 0;
}
BRPC项目自带范例:BRPC/example