### Start server with default options Source: https://github.com/apache/brpc/blob/master/docs/en/server.md Starts the brpc server listening on the specified IP and port using default server options. Suitable for basic server setups. ```c++ int Start(const char* ip_and_port_str, const ServerOptions* opt); int Start(EndPoint ip_and_port, const ServerOptions* opt); int Start(int port, const ServerOptions* opt); int Start(const char *ip_str, PortRange port_range, const ServerOptions *opt); // r32009后增加 ``` -------------------------------- ### Build Couchbase C++ Examples Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Navigate to the example directory and use make to build the Couchbase C++ client examples. ```bash cd example/couchbase_c++/ make ``` -------------------------------- ### Start server with custom options Source: https://github.com/apache/brpc/blob/master/docs/en/server.md Starts the brpc server with custom server options. Allows fine-tuning of server behavior by setting various options before starting. ```c++ brpc::ServerOptions options; // with default values options.xxx = yyy; ... server.Start(..., &options); ``` -------------------------------- ### Run brpc Echo Example Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Builds and runs the echo server and client examples. The examples link brpc statically by default. To link the shared version, use `LINK_SO=1 make`. ```shell $ cd example/echo_c++ $ make $ ./echo_server & $ ./echo_client ``` -------------------------------- ### Start Server with Options Source: https://github.com/apache/brpc/blob/master/docs/cn/server.md Start the brpc server on a specified IP and port, with optional configurations. ServerOptions can be used to customize behavior. ```c++ brpc::ServerOptions options; // 包含了默认值 options.xxx = yyy; ... server.Start(..., &options); ``` -------------------------------- ### Build and Run RedisClusterClient Example Source: https://github.com/apache/brpc/blob/master/docs/en/redis_client.md Builds and runs a client example for RedisClusterChannel. This demonstrates bootstrapping from seed nodes, auto-redirection, topology refresh, and sync/async calls. ```bash cd example/redis_c++ make redis_cluster_client ./redis_cluster_client \ --seeds=127.0.0.1:7000,127.0.0.1:7001 \ --max_redirect=5 \ --timeout_ms=1000 ``` -------------------------------- ### Couchbase Upsert and Get Example Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Demonstrates how to perform an upsert operation and then verify it with a get operation on a Couchbase document. ```cpp std::string updated_value = R"({\"operation\": \"upsert\", \"version\": 2})"; brpc::CouchbaseOperations::Result update_result = couchbase_ops.upsert(upsert_key, updated_value); // Verify with GET brpc::CouchbaseOperations::Result check_result = couchbase_ops.get(upsert_key); ``` -------------------------------- ### Run Multithreaded Couchbase Client Example Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Execute the multithreaded Couchbase client example using the high-level API. ```bash ./multithreaded_couchbase_client ``` -------------------------------- ### Install Profiler Dependencies on Ubuntu Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs libgoogle-perftools-dev to enable CPU and heap profilers in brpc examples. This is needed if you plan to use profiling features. ```shell sudo apt-get install -y libgoogle-perftools-dev ``` -------------------------------- ### Install Trackme Server Source: https://github.com/apache/brpc/blob/master/tools/trackme_server/CMakeLists.txt Installs the built trackme_server executable to the runtime destination directory. ```cmake install(TARGETS trackme_server RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) ``` -------------------------------- ### Run brpc Examples on MacOS Source: https://github.com/apache/brpc/blob/master/docs/cn/getting_started.md Compiles and runs the echo server and client example. Use `LINK_SO=1 make` to link against the shared library instead of the static library. ```shell cd example/echo_c++ make ./echo_server & ./echo_client ``` ```shell make clean LINK_SO=1 make ``` -------------------------------- ### Run Traditional bRPC Couchbase Client Example Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Execute the traditional bRPC client example using the low-level API. ```bash ./traditional_brpc_couchbase_client ``` -------------------------------- ### Run Single-Threaded Couchbase Client Example Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Execute the single-threaded Couchbase client example using the high-level API. ```bash ./couchbase_client ``` -------------------------------- ### Build RDMA performance examples with bazel Source: https://github.com/apache/brpc/blob/master/docs/en/rdma.md Build the RDMA performance server and client examples using bazel. This requires setting the BRPC_WITH_RDMA build flag. ```bash # Server bazel build --define=BRPC_WITH_RDMA=true example:rdma_performance_server # Client bazel build --define=BRPC_WITH_RDMA=true example:rdma_performance_client ``` -------------------------------- ### Start Echo Servers Source: https://github.com/apache/brpc/blob/master/docs/cn/combo_channel.md Start multiple echo servers on specified ports. Each server reports received traffic per partition. ```bash $ ./echo_server -server_num 3 TRACE: 09-06 10:40:39: * 0 server.cpp:159] EchoServer is serving on port=8004 TRACE: 09-06 10:40:39: * 0 server.cpp:159] EchoServer is serving on port=8005 TRACE: 09-06 10:40:39: * 0 server.cpp:159] EchoServer is serving on port=8006 TRACE: 09-06 10:40:40: * 0 server.cpp:192] S[0]=0 S[1]=0 S[2]=0 [total=0] TRACE: 09-06 10:40:41: * 0 server.cpp:192] S[0]=0 S[1]=0 S[2]=0 [total=0] TRACE: 09-06 10:40:42: * 0 server.cpp:192] S[0]=0 S[1]=0 S[2]=0 [total=0] ``` -------------------------------- ### Install Common Dependencies on Ubuntu/LinuxMint/WSL Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs essential development packages including git, g++, make, and libraries for gflags, protobuf, and leveldb. Ensure these are installed before compiling brpc. ```shell sudo apt-get install -y git g++ make libssl-dev libgflags-dev libprotobuf-dev libprotoc-dev protobuf-compiler libleveldb-dev ``` -------------------------------- ### Install Static Library Source: https://github.com/apache/brpc/blob/master/src/CMakeLists.txt Installs the 'brpc-static' library to the appropriate runtime, library, and archive destinations. ```cmake install(TARGETS brpc-static RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) ``` -------------------------------- ### Build a Server with brpc Source: https://github.com/apache/brpc/blob/master/docs/en/overview.md Include brpc/server.h to build a server. Refer to the example for implementation details. ```cpp #include "brpc/server.h" // ... // example: https://github.com/apache/brpc/blob/master/example/echo_c++/server.cpp ``` -------------------------------- ### Install Thrift on Linux Source: https://github.com/apache/brpc/blob/master/docs/en/thrift.md Steps to install Thrift version 0.22.0 on a Linux system, including downloading, compiling, and installing the necessary libraries and tools. ```bash wget https://downloads.apache.org/thrift/0.22.0/thrift-0.22.0.tar.gz tar -xf thrift-0.22.0.tar.gz cd thrift-0.22.0/ ./bootstrap.sh ./configure --prefix=/usr --with-ruby=no --with-python=no --with-java=no --with-go=no --with-perl=no --with-php=no --with-csharp=no --with-erlang=no --with-lua=no --with-nodejs=no --with-rs=no --with-py3=no CXXFLAGS='-Wno-error' make CPPFLAGS=-DFORCE_BOOST_SMART_PTR -j 4 -s sudo make install ``` -------------------------------- ### Execute Multiple Couchbase Operations in a Pipeline Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Demonstrates how to initiate a pipeline, add various CRUD operations (ADD, UPSERT, GET, DELETE), and execute them in a single network call. Includes error handling for pipeline setup and processing results in order. ```cpp // Begin a new pipeline if (!couchbase_ops.beginPipeline()) { LOG(ERROR) << "Failed to begin pipeline"; return -1; } // Add multiple operations to the pipeline (not executed yet) bool success = true; success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::ADD, "key1", "value1"); success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::UPSERT, "key2", "value2"); success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::GET, "key1"); success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::DELETE, "key3"); if (!success) { couchbase_ops.clearPipeline(); // Clean up on error return -1; } // Execute all operations in a single network call std::vector results = couchbase_ops.executePipeline(); // Process results in the same order as requests for (size_t i = 0; i < results.size(); ++i) { if (results[i].success) { std::cout << "Operation " << i << " succeeded" << std::endl; if (!results[i].value.empty()) { std::cout << "Value: " << results[i].value << std::endl; } } else { std::cout << "Operation " << i << " failed: " << results[i].error_message << std::endl; } } ``` -------------------------------- ### Basic Pipeline Usage Example Source: https://github.com/apache/brpc/blob/master/docs/en/couchbase_example.md Demonstrates how to initiate a pipeline, add multiple operations, execute them, and process the results. ```APIDOC ## Basic Pipeline Usage Example Demonstrates how to initiate a pipeline, add multiple operations, execute them, and process the results. ```cpp // Begin a new pipeline if (!couchbase_ops.beginPipeline()) { LOG(ERROR) << "Failed to begin pipeline"; return -1; } // Add multiple operations to the pipeline (not executed yet) bool success = true; success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::ADD, "key1", "value1"); success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::UPSERT, "key2", "value2"); success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::GET, "key1"); success &= couchbase_ops.pipelineRequest(brpc::CouchbaseOperations::DELETE, "key3"); if (!success) { couchbase_ops.clearPipeline(); // Clean up on error return -1; } // Execute all operations in a single network call std::vector results = couchbase_ops.executePipeline(); // Process results in the same order as requests for (size_t i = 0; i < results.size(); ++i) { if (results[i].success) { std::cout << "Operation " << i << " succeeded" << std::endl; if (!results[i].value.empty()) { std::cout << "Value: " << results[i].value << std::endl; } } else { std::cout << "Operation " << i << " failed: " << results[i].error_message << std::endl; } } ``` ``` -------------------------------- ### Thrift Client Access Example Source: https://github.com/apache/brpc/blob/master/docs/en/thrift.md A C++ example demonstrating how to create a brpc channel with Thrift protocol, initialize a ThriftStub, and make a synchronous RPC call to a Thrift server. ```c++ #include #include // Defines ThriftStub ... DEFINE_string(server, "0.0.0.0:8019", "IP Address of thrift server"); DEFINE_string(load_balancer, "", "The algorithm for load balancing"); ... brpc::ChannelOptions options; options.protocol = brpc::PROTOCOL_THRIFT; brpc::Channel thrift_channel; if (thrift_channel.Init(Flags_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) { LOG(ERROR) << "Fail to initialize thrift channel"; return -1; } brpc::ThriftStub stub(&thrift_channel); ... // example::[EchoRequest/EchoResponse] are types generated by thrift example::EchoRequest req; example::EchoResponse res; req.data = "hello"; stub.CallMethod("Echo", &cntl, &req, &res, NULL); if (cntl.Failed()) { LOG(ERROR) << "Fail to send thrift request, " << cntl.ErrorText(); return -1; } ``` -------------------------------- ### Start Server with UDS or IPv6 Address Source: https://github.com/apache/brpc/blob/master/docs/cn/endpoint.md Shows how to start a brpc server listening on a UDS path or an IPv6 address. Use the appropriate string format for the listen address. ```cpp server.Start("unix:path.sock", options); // Start server listening on UDS address server.Start("[::0]:8086", options); // Start server listening on IPv6 address ``` -------------------------------- ### HTTP Naming Service Example Source: https://github.com/apache/brpc/blob/master/docs/en/client.md Provides an example of using an HTTP URL for naming service, connecting to servers under a specified domain. This leverages DNS versatility. ```text http://www.baidu.com:80 ``` -------------------------------- ### HTTPS Naming Service Example Source: https://github.com/apache/brpc/blob/master/docs/en/client.md Shows an example of using an HTTPS URL for naming service, similar to HTTP but with encrypted SSL connections. ```text https://www.baidu.com:443 ``` -------------------------------- ### Install Shared Library Source: https://github.com/apache/brpc/blob/master/src/CMakeLists.txt Installs the 'brpc-shared' library to the appropriate runtime, library, and archive destinations. ```cmake install(TARGETS brpc-shared RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) ``` -------------------------------- ### Install gflags, protobuf, and leveldb on Fedora/CentOS Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs development packages for gflags, protobuf, and leveldb on Fedora/CentOS systems. These are required for compiling brpc. ```shell sudo yum install gflags-devel protobuf-devel protobuf-compiler leveldb-devel ``` -------------------------------- ### Configure and Start BRPC Server with Thrift Service Source: https://github.com/apache/brpc/blob/master/docs/en/thrift.md Set the implemented Thrift service to `brpc::ServerOptions.thrift_service` and configure server options like idle timeout and maximum concurrency. Then, start the server on the specified port. ```c++ brpc::Server server; brpc::ServerOptions options; options.thrift_service = new EchoServiceImpl; options.idle_timeout_sec = FLAGS_idle_timeout_s; options.max_concurrency = FLAGS_max_concurrency; // Start the server. if (server.Start(FLAGS_port, &options) != 0) { LOG(ERROR) << "Fail to start EchoServer"; return -1; } ``` -------------------------------- ### Run brpc Echo Example with CMake Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Builds and runs the echo server and client examples using CMake. To link the shared version, remove `CMakeCache.txt` and configure with `-DLINK_SO=ON`. ```shell $ cd example/echo_c++ $ cmake -B build && cmake --build build -j4 $ ./echo_server & $ ./echo_client ``` -------------------------------- ### Start an ExecutionQueue Source: https://github.com/apache/brpc/blob/master/docs/cn/execution_queue.md Starts an ExecutionQueue with specified options, an execution function, and metadata. The returned ID is a weak reference to the queue, usable for wait-free O(1) location. ```cpp struct ExecutionQueueOptions { ExecutionQueueOptions(); // Execute in resident pthread instead of bthread. default: false. bool use_pthread; // Attribute of the bthread which execute runs on. default: BTHREAD_ATTR_NORMAL // Bthread will be used when executor = NULL and use_pthread == false. bthread_attr_t bthread_attr; // Executor that tasks run on. default: NULL // Note that TaskOptions.in_place_if_possible = false will not work, if implementation of // Executor is in-place(synchronous). Executor * executor; }; // Start a ExecutionQueue. If |options| is NULL, the queue will be created with // default options. // Returns 0 on success, errno otherwise // NOTE: type |T| can be non-POD but must be copy-constructible template int execution_queue_start( ExecutionQueueId* id, const ExecutionQueueOptions* options, int (*execute)(void* meta, TaskIterator& iter), void* meta); ``` -------------------------------- ### Access a Service with brpc Source: https://github.com/apache/brpc/blob/master/docs/en/overview.md Include brpc/channel.h to access services. Refer to the example for implementation details. ```cpp #include "brpc/channel.h" // ... // example: https://github.com/apache/brpc/blob/master/example/echo_c++/client.cpp ``` -------------------------------- ### Install Profiler Dependencies on Fedora/CentOS Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs gperftools-devel for CPU and heap profiling capabilities in brpc examples on Fedora/CentOS. This is an optional dependency. ```shell sudo yum install gperftools-devel ``` -------------------------------- ### Initialize PartitionChannel with Custom Parser Source: https://github.com/apache/brpc/blob/master/docs/en/combo_channel.md Demonstrates the initialization of a PartitionChannel using a custom PartitionParser. It highlights the configuration options available through PartitionChannelOptions, including protocol, timeout, and fail_limit. ```c++ #include ... brpc::PartitionChannel channel; brpc::PartitionChannelOptions options; options.protocol = ...; // PartitionChannelOptions inherits ChannelOptions options.timeout_ms = ...; // Same as above options.fail_limit = 1; // PartitionChannel's own settting, which means the same as that of // ParalellChannel. fail_limit=1 means the overall RPC will fail // as long as only 1 paratition fails if (channel.Init(num_partition_kinds, new MyPartitionParser(), server_address, load_balancer, &options) != 0) { LOG(ERROR) << "Fail to init PartitionChannel"; return -1; } // The RPC interface is the same as regular Channel ``` -------------------------------- ### Example of exported bvar data Source: https://github.com/apache/brpc/blob/master/docs/en/bvar_c++.md This is an example of the content found in the bvar dump file, showing various metrics like RPC counts and server start times. ```text $ cat bvar.echo_server.data rpc_server_8002_builtin_service_count : 20 rpc_server_8002_connection_count : 1 rpc_server_8002_nshead_service_adaptor : brpc::policy::NovaServiceAdaptor rpc_server_8002_service_count : 1 rpc_server_8002_start_time : 2015/07/24-21:08:03 rpc_server_8002_uptime_ms : 14740954 ``` -------------------------------- ### Query bvars by name using curl Source: https://github.com/apache/brpc/blob/master/docs/en/vars.md Access bvars directly from the terminal using curl. This example retrieves all bvars starting with 'bthread'. ```shell $ curl brpc.baidu.com:8765/vars/bthread* bthread_creation_count : 125134 bthread_creation_latency : 3 bthread_creation_latency_50 : 3 bthread_creation_latency_90 : 5 bthread_creation_latency_99 : 7 bthread_creation_latency_999 : 12 bthread_creation_latency_9999 : 12 bthread_creation_latency_cdf : "click to view" bthread_creation_latency_percentiles : "[3,5,7,12]" bthread_creation_max_latency : 7 bthread_creation_qps : 100 bthread_group_status : "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " bthread_num_workers : 24 bthread_worker_usage : 1.01056 ``` -------------------------------- ### Status Code Handling Source: https://github.com/apache/brpc/blob/master/docs/en/http_service.md Explains how to get and set HTTP status codes and reason phrases for responses, including an example of implementing redirection. ```APIDOC ## Status Code Status code is a special field in HTTP response to store processing result of the http request. Possible values are defined in [http_status_code.h](https://github.com/apache/brpc/blob/master/src/brpc/http_status_code.h). ```c++ // Get Status Code if (cntl->http_response().status_code() == brpc::HTTP_STATUS_NOT_FOUND) { LOG(FATAL) << "FAILED: " << controller.http_response().reason_phrase(); } ... // Set Status code cntl->http_response().set_status_code(brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR); cntl->http_response().set_status_code(brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR, "My explanation of the error..."); ``` For example, following code implements redirection with status code 302: ```c++ cntl->http_response().set_status_code(brpc::HTTP_STATUS_FOUND); cntl->http_response().SetHeader("Location", "http://bj.bs.bae.baidu.com/family/image001(4979).jpg"); ``` ``` -------------------------------- ### Initialize Naming Service with brpc Source: https://github.com/apache/brpc/blob/master/docs/en/overview.md Initialize naming services with a simple string format. Examples include BNS, DNS, and local file lists. ```cpp Init("bns://node-name", ...) Init("http://domain-name", ...) Init("file:///home/work/server.list", ...) ``` -------------------------------- ### Install GnuPG on macOS Source: https://github.com/apache/brpc/blob/master/community/release_en.md Installs GnuPG using Homebrew on macOS. Ensure GnuPG is installed before proceeding with key generation. ```bash brew install gnupg ``` -------------------------------- ### Install Dependencies on MacOS Source: https://github.com/apache/brpc/blob/master/docs/cn/getting_started.md Installs necessary dependencies for brpc compilation on MacOS using Homebrew. Includes optional installation for profilers and gtest. ```shell brew install ./homebrew-formula/protobuf.rb brew install openssl git gnu-getopt coreutils gflags leveldb ``` ```shell brew install gperftools ``` ```shell git clone https://github.com/google/googletest -b release-1.10.0 && cd googletest/googletest && mkdir build && cd build && cmake -DCMAKE_CXX_FLAGS="-std=c++11" .. && make ``` -------------------------------- ### Redis CLI Tool Demonstration Source: https://github.com/apache/brpc/blob/master/docs/en/redis_client.md This example demonstrates a command-line tool that mimics the official redis-cli, showcasing brpc's ability to communicate with Redis servers. It allows interactive execution of Redis commands. ```bash $ ./redis_cli __ _ __ / /_ ____ _(_)___/ /_ __ _________ _____ / __ \/ __ `/ / __ / / / /_____/ ___/ __ \/ ___/ / /_/ / /_/ / / /_/ / /_/ /_____/ / / /_/ / /__ /_.___/\__,_/_/\__,_/\__,_/ /_/ / .___/\___/ /_/ This command-line tool mimics the look-n-feel of official redis-cli, as a demonstration of brpc's capability of talking to redis server. The output and behavior is not exactly same with the official one. redis 127.0.0.1:6379> mset key1 foo key2 bar key3 17 OK redis 127.0.0.1:6379> mget key1 key2 key3 ["foo", "bar", "17"] redis 127.0.0.1:6379> incrby key3 10 (integer) 27 redis 127.0.0.1:6379> client setname brpc-cli OK redis 127.0.0.1:6379> client getname "brpc-cli" ``` -------------------------------- ### Project and Dependency Setup Source: https://github.com/apache/brpc/blob/master/example/multi_threaded_echo_fns_c++/CMakeLists.txt Initializes the CMake project and sets up essential paths and includes for brpc, protobuf, gflags, and leveldb. It also handles finding libraries like OpenSSL and gperftools. ```cmake cmake_minimum_required(VERSION 2.8.10) project(multi_threaded_echo_fns_c++ C CXX) option(LINK_SO "Whether examples are linked dynamically" OFF) execute_process( COMMAND bash -c "find ${PROJECT_SOURCE_DIR}/../.. -type d -regex ".*output/include$" | head -n1 | xargs dirname | tr -d '\n'" OUTPUT_VARIABLE OUTPUT_PATH ) set(CMAKE_PREFIX_PATH ${OUTPUT_PATH}) include(FindThreads) include(FindProtobuf) protobuf_generate_cpp(PROTO_SRC PROTO_HEADER echo.proto) # include PROTO_HEADER include_directories(${CMAKE_CURRENT_BINARY_DIR}) # Search for libthrift* by best effort. If it is not found and brpc is # compiled with thrift protocol enabled, a link error would be reported. find_library(THRIFT_LIB NAMES thrift) if (NOT THRIFT_LIB) set(THRIFT_LIB "") endif() find_path(GPERFTOOLS_INCLUDE_DIR NAMES gperftools/heap-profiler.h) find_library(GPERFTOOLS_LIBRARIES NAMES tcmalloc_and_profiler) include_directories(${GPERFTOOLS_INCLUDE_DIR}) find_path(BRPC_INCLUDE_PATH NAMES brpc/server.h) if(LINK_SO) find_library(BRPC_LIB NAMES brpc) else() find_library(BRPC_LIB NAMES libbrpc.a brpc) endif() if((NOT BRPC_INCLUDE_PATH) OR (NOT BRPC_LIB)) message(FATAL_ERROR "Fail to find brpc") endif() include_directories(${BRPC_INCLUDE_PATH}) find_path(GFLAGS_INCLUDE_PATH gflags/gflags.h) find_library(GFLAGS_LIBRARY NAMES gflags libgflags) if((NOT GFLAGS_INCLUDE_PATH) OR (NOT GFLAGS_LIBRARY)) message(FATAL_ERROR "Fail to find gflags") endif() include_directories(${GFLAGS_INCLUDE_PATH}) if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") include(CheckFunctionExists) CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME) if(NOT HAVE_CLOCK_GETTIME) set(DEFINE_CLOCK_GETTIME "-DNO_CLOCK_GETTIME_IN_MAC") endif() endif() set(CMAKE_CXX_FLAGS "${DEFINE_CLOCK_GETTIME} -DNDEBUG -O2 -D__const__=__unused__ -pipe -W -Wall -Wno-unused-parameter -fPIC -fno-omit-frame-pointer") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBRPC_ENABLE_CPU_PROFILER") if(CMAKE_VERSION VERSION_LESS "3.1.3") if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") endif() if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") endif() else() set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) endif() find_path(LEVELDB_INCLUDE_PATH NAMES leveldb/db.h) find_library(LEVELDB_LIB NAMES leveldb) if ((NOT LEVELDB_INCLUDE_PATH) OR (NOT LEVELDB_LIB))) message(FATAL_ERROR "Fail to find leveldb") endif() include_directories(${LEVELDB_INCLUDE_PATH}) if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") set(OPENSSL_ROOT_DIR "/usr/local/opt/openssl" # Homebrew installed OpenSSL ) endif() find_package(OpenSSL) include_directories(${OPENSSL_INCLUDE_DIR}) ``` -------------------------------- ### Install parallel_http Executable Source: https://github.com/apache/brpc/blob/master/tools/parallel_http/CMakeLists.txt Installs the parallel_http executable to the runtime destination directory defined by CMAKE_INSTALL_BINDIR. This makes the tool available in the system's PATH after installation. ```cmake install(TARGETS parallel_http RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) ``` -------------------------------- ### Start Dummy Server at Port (C++) Source: https://github.com/apache/brpc/blob/master/docs/en/dummy_server.md Manually add this code snippet at the program entry when brpc is not used at all. Ensure brpc is downloaded and compiled first. ```c++ #include ... int main() { ... brpc::StartDummyServerAt(8888/*port*/); ... } ``` -------------------------------- ### File Naming Service Example Source: https://github.com/apache/brpc/blob/master/docs/en/client.md Shows the format for a file-based naming service, where server addresses are listed in a file. Supports comments and tags for instances. ```text # This line is ignored 10.24.234.17:8080 tag1 # a comment 10.24.234.17:8090 tag2 # an instance different from the instance on last line 10.24.234.18:8080 10.24.234.19:8080 ``` -------------------------------- ### Check GnuPG Version Source: https://github.com/apache/brpc/blob/master/community/release_en.md Verifies the installed GnuPG version. This command is useful after installation or to confirm compatibility. ```bash gpg --version ``` -------------------------------- ### List Naming Service Example Source: https://github.com/apache/brpc/blob/master/docs/en/client.md Demonstrates the format for a list-based naming service, where server addresses are comma-separated. Tags can be appended to addresses. ```text list://db-bce-81-3-186.db01:7000,m1-bce-44-67-72.m1:7000,cp01-rd-cos-006.cp01:7000 ``` -------------------------------- ### GPG Key Generation Interactive Prompt Source: https://github.com/apache/brpc/blob/master/community/release_en.md Example output from the `gpg --full-gen-key` command, illustrating the interactive prompts for key creation and the resulting key details. ```text gpg (GnuPG) 2.3.1; Copyright (C) 2021 Free Software Foundation, Inc. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Please select what kind of key you want: (1) RSA and RSA (2) DSA and Elgamal (3) DSA (sign only) (4) RSA (sign only) (9) ECC (sign and encrypt) *default* (10) ECC (sign only) (14) Existing key from card Your selection? 1 RSA keys may be between 1024 and 4096 bits long. What keysize do you want? (3072) 4096 Requested keysize is 4096 bits Please specify how long the key should be valid. 0 = key does not expire = key expires in n days w = key expires in n weeks m = key expires in n months y = key expires in n years Key is valid for? (0) 0 Key does not expire at all Is this correct? (y/N) y GnuPG needs to construct a user ID to identify your key. Real name: LorinLee Email address: lorinlee@apache.org Comment: lorinlee's key You selected this USER-ID: "LorinLee (lorinlee's key) " Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O You need a Passphrase to protect your secret key. # Input password We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy. gpg: key 92E18A11B6585834 marked as ultimately trusted gpg: revocation certificate stored as '/Users/lilei/.gnupg/openpgp-revocs.d/C30F211F071894258497F46392E18A11B6585834.rev' public and secret key created and signed. pub rsa4096 2021-10-17 [SC] C30F211F071894258497F46392E18A11B6585834 uid LorinLee (lorinlee's key) sub rsa4096 2021-10-17 [E] ``` -------------------------------- ### Initialize MySQL Data Directory Source: https://github.com/apache/brpc/blob/master/test/README_mysql_auth.md Prepare a data directory for a MySQL server instance. This command should be run once per fresh MySQL instance and is part of setting up an already-running server for testing. ```sh export MYSQL_DATA=/tmp/brpc_mysql_e2e export MYSQL_PORT=13306 rm -rf "$MYSQL_DATA" && mkdir -p "$MYSQL_DATA" mysqld --initialize-insecure --datadir="$MYSQL_DATA" --log-error="$MYSQL_DATA/init.err" ``` -------------------------------- ### Start MySQL Server (Verbose) Source: https://github.com/apache/brpc/blob/master/test/README_mysql_auth.md Launch a MySQL server instance with verbose logging enabled. This is used when testing against an already-running server, allowing observation of the handshake process. Ensure the server is configured with the correct data directory and port. ```sh mysqld --datadir="$MYSQL_DATA" --port="$MYSQL_PORT" \ --socket="$MYSQL_DATA/mysqld.sock" --bind-address=127.0.0.1 \ --mysqlx=OFF --log-error-verbosity=3 \ --general-log=1 --general-log-file="$MYSQL_DATA/general.log" ``` -------------------------------- ### Install GTest on Fedora/CentOS Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs the gtest-devel package for running tests. Note that gtest might require manual compilation on some older versions. ```shell sudo yum install gtest-devel ``` -------------------------------- ### Client Output with 3-partition Source: https://github.com/apache/brpc/blob/master/docs/cn/combo_channel.md Observe client-side logs showing connection to the server and RPC request rates. The QPS and latency indicate normal operation. ```bash $ ./echo_client TRACE: 09-06 10:51:10: * 0 src/brpc/policy/file_naming_service.cpp:83] Got 3 unique addresses from `server_list' TRACE: 09-06 10:51:10: * 0 src/brpc/socket.cpp:779] Connected to 0.0.0.0:8004 via fd=3 SocketId=0 self_port=46544 TRACE: 09-06 10:51:11: * 0 client.cpp:226] Sending EchoRequest at qps=132472 latency=371 TRACE: 09-06 10:51:12: * 0 client.cpp:226] Sending EchoRequest at qps=132658 latency=370 TRACE: 09-06 10:51:13: * 0 client.cpp:226] Sending EchoRequest at qps=133208 latency=369 ``` -------------------------------- ### Install brpc with vcpkg Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs brpc using the vcpkg package manager. This method supports cross-platform builds and simplifies dependency management. ```shell $ git clone https://github.com/microsoft/vcpkg.git $ ./bootstrap-vcpkg.bat # for powershell $ ./bootstrap-vcpkg.sh # for bash $ ./vcpkg install brpc ``` -------------------------------- ### Install LevelDB for Static Linking on Ubuntu Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs libsnappy-dev, which is required for statically linking leveldb. This is an optional step depending on your linking requirements. ```shell sudo apt-get install -y libsnappy-dev ``` -------------------------------- ### Bvar Naming Examples Source: https://github.com/apache/brpc/blob/master/docs/en/bvar_c++.md Examples demonstrating the recommended naming convention for bvars: module_class_indicator. This helps avoid name duplication across different modules. ```plaintext iobuf_block_count : 29 # module=iobuf class=block indicator=count iobuf_block_memory : 237568 # module=iobuf class=block indicator=memory process_memory_resident : 34709504 # module=process class=memory indicator=resident process_memory_shared : 6844416 # module=process class=memory indicator=shared rpc_channel_connection_count : 0 # module=rpc class=channel_connection indicator=count rpc_controller_count : 1 # module=rpc class=controller indicator=count rpc_socket_count : 6 # module=rpc class=socket indicator=count ``` -------------------------------- ### Run Echo Server/Client with UDS or IPv6 Source: https://github.com/apache/brpc/blob/master/docs/cn/endpoint.md Provides command-line examples for running the echo server and client with UDS or IPv6 addresses. Use the '-listen_addr' for the server and '-server' for the client. ```bash ./echo_server -listen_addr='unix:path.sock' & # Start Server listening on UDS address ./echo_server -listen_addr='[::0]:8080' & # Start Server listening on IPv6 port ./echo_client -server='unix:path.sock' # Start Client accessing UDS address ./echo_client -server='[::1]:8080' # Start Client accessing IPv6 port ``` -------------------------------- ### Create and Use bthread-local Data Source: https://github.com/apache/brpc/blob/master/docs/en/server.md Demonstrates creating and accessing bthread-local data using bthread_key_create, bthread_getspecific, and bthread_setspecific. Ensure that the key is created before use and that memory is managed appropriately. ```cpp google::protobuf::Closure* done) { ... // You can create bthread-local data for your own. // The interfaces are similar with pthread equivalence: // pthread_key_create -> bthread_key_create // pthread_key_delete -> bthread_key_delete // pthread_getspecific -> bthread_getspecific // pthread_setspecific -> bthread_setspecific MyThreadLocalData* tls2 = static_cast(bthread_getspecific(_tls2_key)); if (tls2 == NULL) { tls2 = new MyThreadLocalData; CHECK_EQ(0, bthread_setspecific(_tls2_key, tls2)); } ... ``` -------------------------------- ### Basic Logging with brpc Source: https://github.com/apache/brpc/blob/master/docs/en/streaming_log.md Demonstrates various logging levels and conditional logging macros available in brpc. Use these for different severity and frequency requirements. ```c++ #include LOG(FATAL) << "Fatal error occurred! contexts=" << ...; LOG(WARNING) << "Unusual thing happened ..." << ...; LOG(TRACE) << "Something just took place..." << ...; LOG(TRACE) << "Items:" << noflush; LOG_IF(NOTICE, n > 10) << "This log will only be printed when n > 10"; PLOG(FATAL) << "Fail to call function setting errno"; VLOG(1) << "verbose log tier 1"; CHECK_GT(1, 2) << "1 can't be greater than 2"; LOG_EVERY_SECOND(INFO) << "High-frequent logs"; LOG_EVERY_N(ERROR, 10) << "High-frequent logs"; LOG_FIRST_N(INFO, 20) << "Logs that prints for at most 20 times"; LOG_ONCE(WARNING) << "Logs that only prints once"; ``` -------------------------------- ### Initialize and Add Channels to SelectiveChannel Source: https://github.com/apache/brpc/blob/master/docs/en/combo_channel.md Demonstrates how to initialize a SelectiveChannel and add multiple regular channels to it, each potentially connected to a different naming service. Useful for distributing traffic across distinct sets of servers. ```c++ brpc::SelectiveChannel channel; brpc::ChannelOptions schan_options; schan_options.timeout_ms = FLAGS_timeout_ms; schan_options.max_retry = FLAGS_max_retry; if (channel.Init("c_murmurhash", &schan_options) != 0) { LOG(ERROR) << "Fail to init SelectiveChannel"; return -1; } for (int i = 0; i < 3; ++i) { brpc::Channel* sub_channel = new brpc::Channel; if (sub_channel->Init(ns_node_name[i], "rr", NULL) != 0) { LOG(ERROR) << "Fail to init sub channel " << i; return -1; } if (channel.AddChannel(sub_channel, NULL/*handle for removal*/) != 0) { LOG(ERROR) << "Fail to add sub_channel to channel"; return -1; } } ... XXXService_Stub stub(&channel); stub.FooMethod(&cntl, &request, &response, NULL); ... ``` -------------------------------- ### Install Common Dependencies on Fedora/CentOS Source: https://github.com/apache/brpc/blob/master/docs/en/getting_started.md Installs necessary development packages on Fedora/CentOS, including git, gcc-c++, make, and OpenSSL. Ensure EPEL repository is enabled for CentOS. ```shell sudo yum install epel-release sudo yum install git gcc-c++ make openssl-devel ``` -------------------------------- ### Get Client Address and Port Source: https://github.com/apache/brpc/blob/master/docs/cn/client.md Use local_side() to get the client's address and port after an RPC has finished. This is available from r31384 onwards. The output can be logged or printed. ```c++ LOG(INFO) << "local_side=" << cntl->local_side(); printf("local_side=%s\n", butil::endpoint2str(cntl->local_side()).c_str()); ``` -------------------------------- ### Initialize Channel with Custom Options Source: https://github.com/apache/brpc/blob/master/docs/en/client.md Demonstrates how to initialize a brpc::Channel with custom options. Ensure ChannelOptions are initialized before setting custom values. ```c++ brpc::ChannelOptions options; // including default values options.xxx = yyy; ... channel.Init(..., &options); ```