tutorial-15-srpc_pb_proxy.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright (c) 2020 sogou, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #include <signal.h>
  14. #include "echo_pb.srpc.h"
  15. #include "workflow/WFFacilities.h"
  16. #include "srpc/rpc_types.h"
  17. using namespace srpc;
  18. static WFFacilities::WaitGroup wait_group(1);
  19. template<class CLIENT>
  20. class ExampleProxyServiceImpl : public Example::Service
  21. {
  22. public:
  23. ExampleProxyServiceImpl(CLIENT *client)
  24. {
  25. this->client = client;
  26. }
  27. private:
  28. CLIENT *client;
  29. public:
  30. void Echo(EchoRequest *request, EchoResponse *response, RPCContext *context) override
  31. {
  32. printf("Proxy Server Echo() get and transfer request:\n%s\n",
  33. request->DebugString().c_str());
  34. auto *task = this->client->create_Echo_task([response](EchoResponse *resp,
  35. RPCContext *ctx) {
  36. printf("Proxy Server Echo() get and transfer response:\n%s\n",
  37. resp->DebugString().c_str());
  38. if (ctx->success())
  39. *response = std::move(*resp);
  40. });
  41. task->serialize_input(request);
  42. context->get_series()->push_back(task);
  43. }
  44. };
  45. static void sig_handler(int signo)
  46. {
  47. wait_group.done();
  48. }
  49. int main()
  50. {
  51. GOOGLE_PROTOBUF_VERIFY_VERSION;
  52. signal(SIGINT, sig_handler);
  53. signal(SIGTERM, sig_handler);
  54. SRPCServer server;
  55. Example::SRPCClient client("127.0.0.1", 1412);
  56. ExampleProxyServiceImpl<Example::SRPCClient> impl(&client);
  57. server.add_service(&impl);
  58. if (server.start(61412) == 0)
  59. {
  60. printf("Proxy server serving on 61412 and redirect to backend server 127.0.0.1:1412\n"
  61. "Try start ./srpc_pb_server as backend and send requests to 61412.\n\n");
  62. wait_group.wait();
  63. server.stop();
  64. }
  65. else
  66. perror("server start");
  67. google::protobuf::ShutdownProtobufLibrary();
  68. return 0;
  69. }