Send Query
Send a KubeMQ Query and receive response data with the C++ SDK in a synchronous request-reply exchange.
Overview
This tutorial builds the RPC half of KubeMQ's request/reply patterns: a query, where the caller blocks for a handler's data payload instead of just a completion status. Reach for it whenever a caller needs an answer — fetching a record, running a lookup, or asking another service to compute a value on demand. You'll run a handler and a sender in the same process to see the full round trip.
The sender builds a request with kubemq::Query::Builder() and calls client->SendQuery(...), which blocks until a reply arrives. client->SubscribeToQueries(...) registers a handler callback; the handler builds a reply with kubemq::QueryReply::Builder().SetRequestId(q.id).SetResponseTo(q.response_to) — copied from the incoming query — plus SetBody(...), sent with client->SendQueryResponse(...). KubeMQ routes that reply back to the caller waiting on it.
Gotchas: the timeout passed to SetTimeout(...) must cover however long the handler takes to run — a slow handler leaves resp_result->executed false even though the handler eventually succeeds. No handler subscribed yet also times out rather than erroring immediately. The body is a plain byte payload you encode yourself, and every status-returning call should be checked with .ok() before dereferencing the result.
Prerequisites
- KubeMQ server running on
localhost:50000 - C++ SDK installed (vcpkg or CMake FetchContent)
- C++17 compiler (GCC 9+, Clang 9+, MSVC 2019+)
Code
// Example: queries/send_query
//
// Demonstrates sending a query and receiving a response with data.
// Unlike commands, queries return a body payload in the response.
//
// Channel: cpp-queries.send-query
// Client ID: cpp-queries-send-query-client
//
// Run with a KubeMQ server on localhost:50000
// (see https://docs.kubemq.io/deploy).
#include <kubemq/kubemq.h>
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
int main() {
std::cout << "[1] Connecting to localhost:50000" << std::endl;
kubemq::ClientOptions options;
options.set_address("localhost", 50000);
options.set_client_id("cpp-queries-send-query-client");
auto client_result = kubemq::Client::Create(options);
if (!client_result.ok()) {
std::cerr << "[ERROR] Failed to create client: " << client_result.status().message()
<< std::endl;
return 1;
}
auto& client = *client_result;
std::string channel = "cpp-queries.send-query";
std::atomic<bool> query_handled{false};
// Subscribe to handle queries and return data.
std::cout << "[2] Subscribing to queries on channel " << channel << std::endl;
auto sub_result = client->SubscribeToQueries(
channel, "",
[&client, &query_handled](const kubemq::QueryReceive& q) {
std::cout << "[4] Query received: channel=" << q.channel << " body=" << q.body
<< std::endl;
// Build and send a response with a JSON body.
auto now_epoch = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
auto reply_result = kubemq::QueryReply::Builder()
.SetRequestId(q.id)
.SetResponseTo(q.response_to)
.SetBody(R"({"result":"data","status":"ok"})")
.SetMetadata("ok")
.SetExecuted(true)
.SetExecutedAt(now_epoch)
.Build();
if (!reply_result.ok()) {
std::cerr << "[ERROR] Build reply: " << reply_result.status().message()
<< std::endl;
return;
}
auto send_status = client->SendQueryResponse(*reply_result);
if (!send_status.ok()) {
std::cerr << "[ERROR] SendQueryResponse: " << send_status.message() << std::endl;
return;
}
query_handled.store(true);
},
[](const kubemq::Status& err) {
std::cerr << "[ERROR] Query subscription error: " << err.message() << std::endl;
});
if (!sub_result.ok()) {
std::cerr << "[ERROR] SubscribeToQueries: " << sub_result.status().message() << std::endl;
return 1;
}
auto& sub = *sub_result;
// Allow subscription to fully establish before sending.
std::this_thread::sleep_for(std::chrono::milliseconds(300));
// Build and send a query with a 10-second timeout.
std::cout << "[3] Sending query to channel " << channel << std::endl;
auto query_build = kubemq::Query::Builder()
.SetChannel(channel)
.SetBody("fetch-data")
.SetTimeout(std::chrono::seconds(10))
.Build();
if (!query_build.ok()) {
std::cerr << "[ERROR] Build query: " << query_build.status().message() << std::endl;
return 1;
}
auto resp_result = client->SendQuery(*query_build);
if (!resp_result.ok()) {
std::cerr << "[ERROR] SendQuery: " << resp_result.status().message() << std::endl;
return 1;
}
std::cout << "[5] Query response: executed=" << std::boolalpha << resp_result->executed
<< " body=" << resp_result->body << std::endl;
// Wait for the handler to finish processing.
std::this_thread::sleep_for(std::chrono::seconds(1));
// Cancel the subscription explicitly.
// Note: The Subscription destructor also calls Cancel(), but explicit
// cleanup is shown here for clarity and to match Go's defer pattern.
sub->Cancel();
std::cout << "[6] Subscription cancelled" << std::endl;
auto close_status = client->Close();
if (!close_status.ok()) {
std::cerr << "[ERROR] Close failed: " << close_status.message() << std::endl;
return 1;
}
std::cout << "[7] Client closed" << std::endl;
return 0;
}How It Works
- Subscribes to handle queries and return data in the response body.
- The handler builds a
QueryReplywith a JSON body and sends it back. - Sends a query using
Query::Builder()with channel, body, and timeout. - Unlike commands, the query response includes a body payload with data.
Related
Was this page helpful?