@zhengyuhong
2017-01-24T12:11:22.000000Z
字数 2436
阅读 2128
code
virtual void Echo(google::protobuf::RpcController* cntl_base,const example::EchoRequest* request,example::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().baidu::rpc::ClosureGuard done_guard(done);//done表示Echo执行完成后,框架需要执行的后续操作,如果实现异步调用的话,直接返回一个response给client,然后异步执行自定义代码,自定义代码函数执行完之后,再执行done->Run();告诉框架执行后续操作。
// Since we are sending asynchronous RPC (`done' is not NULL),// these objects MUST remain valid until `done' is called.// As a result, we allocate these objects on heapexample::EchoResponse* response = new example::EchoResponse();baidu::rpc::Controller* cntl = new baidu::rpc::Controller();// Notice that you don't have to new request, which can be modified// or destroyed just after stub.Echo is called.example::EchoRequest request;request.set_message("hello world");cntl->set_log_id(log_id ++); // set by userif (FLAGS_send_attachment) {// Set attachment which is wired to network directly instead of// being serialized into protobuf messages.cntl->request_attachment().append("foo");}// We use protobuf utility `NewCallback' to create a closure object// that will call our callback `HandleEchoResponse'. This closure// will automatically delete itself after being called oncegoogle::protobuf::Closure* done = baidu::rpc::NewCallback(&HandleEchoResponse, cntl, response);stub.Echo(cntl, &request, response, done);// This is an asynchronous RPC, so we can only fetch the result// inside the callback
done是回调闭包,必须创建在堆上,response是回调函数的返回参数,也必须创建在堆上,如果在栈上分配的话,在触发回调函数时,内存已经失效了。
void Echo(google::protobuf::RpcController* cntl_base,const HttpRequest*,HttpResponse*,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().baidu::rpc::ClosureGuard done_guard(done);baidu::rpc::Controller* cntl =static_cast<baidu::rpc::Controller*>(cntl_base);// Fill response.cntl->http_response().set_content_type("text/plain");base::IOBufBuilder os;os << "queries:";for (baidu::rpc::URI::QueryIterator it = cntl->http_request().uri().QueryBegin();it != cntl->http_request().uri().QueryEnd(); ++it) {os << ' ' << it->first << '=' << it->second;}os << "\nbody: " << cntl->request_attachment() << '\n';os.move_to(cntl->response_attachment());}
注意在http服务端中Echo函数参数const HttpRequest*, HttpResponse*,,HttpRequest,Response是没有成员变量。
