client.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // Copyright (c) 2014 Baidu, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // A client sending requests to servers(discovered by naming service) by multiple threads.
  15. #include <gflags/gflags.h>
  16. #include <bthread/bthread.h>
  17. #include <butil/logging.h>
  18. #include <butil/string_printf.h>
  19. #include <butil/time.h>
  20. #include <butil/macros.h>
  21. #include <brpc/channel.h>
  22. #include <brpc/server.h>
  23. #include <deque>
  24. #include "echo.pb.h"
  25. DEFINE_int32(thread_num, 50, "Number of threads to send requests");
  26. DEFINE_bool(use_bthread, false, "Use bthread to send requests");
  27. DEFINE_int32(attachment_size, 0, "Carry so many byte attachment along with requests");
  28. DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
  29. DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
  30. DEFINE_string(server, "file://server_list", "Addresses of servers");
  31. DEFINE_string(load_balancer, "rr", "Name of load balancer");
  32. DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
  33. DEFINE_int32(backup_timeout_ms, -1, "backup timeout in milliseconds");
  34. DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)");
  35. DEFINE_bool(dont_fail, false, "Print fatal when some call failed");
  36. DEFINE_int32(dummy_port, 0, "Launch dummy server at this port");
  37. DEFINE_string(http_content_type, "application/json", "Content type of http request");
  38. std::string g_attachment;
  39. bvar::LatencyRecorder g_latency_recorder("client");
  40. bvar::Adder<int> g_error_count("client_error_count");
  41. butil::static_atomic<int> g_sender_count = BUTIL_STATIC_ATOMIC_INIT(0);
  42. static void* sender(void* arg) {
  43. // Normally, you should not call a Channel directly, but instead construct
  44. // a stub Service wrapping it. stub can be shared by all threads as well.
  45. example::EchoService_Stub stub(static_cast<google::protobuf::RpcChannel*>(arg));
  46. int log_id = 0;
  47. while (!brpc::IsAskedToQuit()) {
  48. // We will receive response synchronously, safe to put variables
  49. // on stack.
  50. example::EchoRequest request;
  51. example::EchoResponse response;
  52. brpc::Controller cntl;
  53. const int thread_index = g_sender_count.fetch_add(1, butil::memory_order_relaxed);
  54. const int input = ((thread_index & 0xFFF) << 20) | (log_id & 0xFFFFF);
  55. request.set_value(input);
  56. cntl.set_log_id(log_id ++); // set by user
  57. if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c") {
  58. // Set attachment which is wired to network directly instead of
  59. // being serialized into protobuf messages.
  60. cntl.request_attachment().append(g_attachment);
  61. } else {
  62. cntl.http_request().set_content_type(FLAGS_http_content_type);
  63. }
  64. // Because `done'(last parameter) is NULL, this function waits until
  65. // the response comes back or error occurs(including timedout).
  66. stub.Echo(&cntl, &request, &response, NULL);
  67. if (!cntl.Failed()) {
  68. CHECK(response.value() == request.value() + 1);
  69. g_latency_recorder << cntl.latency_us();
  70. } else {
  71. g_error_count << 1;
  72. CHECK(brpc::IsAskedToQuit() || !FLAGS_dont_fail)
  73. << "input=(" << thread_index << "," << (input & 0xFFFFF)
  74. << ") error=" << cntl.ErrorText() << " latency=" << cntl.latency_us();
  75. // We can't connect to the server, sleep a while. Notice that this
  76. // is a specific sleeping to prevent this thread from spinning too
  77. // fast. You should continue the business logic in a production
  78. // server rather than sleeping.
  79. bthread_usleep(50000);
  80. }
  81. }
  82. return NULL;
  83. }
  84. int main(int argc, char* argv[]) {
  85. // Parse gflags. We recommend you to use gflags as well.
  86. GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
  87. // A Channel represents a communication line to a Server. Notice that
  88. // Channel is thread-safe and can be shared by all threads in your program.
  89. brpc::Channel channel;
  90. // Initialize the channel, NULL means using default options.
  91. brpc::ChannelOptions options;
  92. options.backup_request_ms = FLAGS_backup_timeout_ms;
  93. options.protocol = FLAGS_protocol;
  94. options.connection_type = FLAGS_connection_type;
  95. options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
  96. options.max_retry = FLAGS_max_retry;
  97. if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {
  98. LOG(ERROR) << "Fail to initialize channel";
  99. return -1;
  100. }
  101. if (FLAGS_attachment_size > 0) {
  102. g_attachment.resize(FLAGS_attachment_size, 'a');
  103. }
  104. if (FLAGS_dummy_port > 0) {
  105. brpc::StartDummyServerAt(FLAGS_dummy_port);
  106. }
  107. std::vector<bthread_t> tids;
  108. tids.resize(FLAGS_thread_num);
  109. if (!FLAGS_use_bthread) {
  110. for (int i = 0; i < FLAGS_thread_num; ++i) {
  111. if (pthread_create(&tids[i], NULL, sender, &channel) != 0) {
  112. LOG(ERROR) << "Fail to create pthread";
  113. return -1;
  114. }
  115. }
  116. } else {
  117. for (int i = 0; i < FLAGS_thread_num; ++i) {
  118. if (bthread_start_background(
  119. &tids[i], NULL, sender, &channel) != 0) {
  120. LOG(ERROR) << "Fail to create bthread";
  121. return -1;
  122. }
  123. }
  124. }
  125. while (!brpc::IsAskedToQuit()) {
  126. sleep(1);
  127. LOG(INFO) << "Sending EchoRequest at qps=" << g_latency_recorder.qps(1)
  128. << " latency=" << g_latency_recorder.latency(1);
  129. }
  130. LOG(INFO) << "EchoClient is going to quit";
  131. for (int i = 0; i < FLAGS_thread_num; ++i) {
  132. if (!FLAGS_use_bthread) {
  133. pthread_join(tids[i], NULL);
  134. } else {
  135. bthread_join(tids[i], NULL);
  136. }
  137. }
  138. return 0;
  139. }