在C++中,實現(xiàn)RPC(遠程過程調(diào)用)通常涉及以下步驟:
以下是一個簡單的示例,使用gRPC框架實現(xiàn)遠程調(diào)用:
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
protoc
命令生成C++代碼。#include <iostream>
#include <memory>
#include "helloworld.pb.h"
using namespace std;
using grpc::Server;
using grpc::ServerBuilder;
using helloworld::Greeter;
using helloworld::HelloRequest;
using helloworld::HelloReply;
class GreeterServiceImpl : public Greeter::Service {
public:
void SayHello(const HelloRequest* request, HelloReply* reply, ServerContext* context) override {
reply->set_message("Hello " + request->name());
}
};
int main(int argc, char** argv) {
ServerBuilder builder;
auto server = builder.AddListeningPort("localhost:50051", grpc::InsecureServerCredentials())
.AddService(new GreeterServiceImpl())
.Build();
server->Start();
server->Wait();
return 0;
}
#include <iostream>
#include <memory>
#include "helloworld.pb.h"
using namespace std;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloRequest;
using helloworld::HelloReply;
int main(int argc, char** argv) {
shared_ptr<GreeterClient> client(new GreeterClient("localhost:50051"));
HelloRequest request;
request.set_name("World");
HelloReply reply;
Status status = client->SayHello(&request, &reply);
if (status.ok()) {
cout << reply.message() << endl;
} else {
cout << "RPC failed: " << status.error_message() << endl;
}
return 0;
}
注意:這個示例使用了gRPC框架和Protocol Buffers,但你可以使用其他RPC框架(如Apache Thrift、RESTful API等)和序列化格式(如JSON、XML等)來實現(xiàn)類似的功能。