Pulsar C++ client
您可以使用 Pulsar C++ 客户端在 C++ 中创建 Pulsar 生产者和消费者。
C++ 客户端中生产者、消费者和 Reader 的所有方法都是线程安全的。
支持的平台
Pulsar C++ client is supported on Linux ,MacOS and Windows platforms.
关于 Doxygen 生成的适用于 C++ 客户端的 API 文档,参阅这里。
系统要求
您需要先安装下列组件才能使用 C++ 客户端:
Linux
编译
- 克隆Pulsar项目仓库
$ git clone https://github.com/apache/pulsar
- 安装所有必要的依赖项。
$ apt-get install cmake libssl-dev libcurl4-openssl-dev liblog4cxx-dev \
libprotobuf-dev protobuf-compiler libboost-all-dev google-mock libgtest-dev libjsoncpp-dev
- 编译并安装 Google 测试。
# libgtest-dev version is 1.18.0 or above
$ cd /usr/src/googletest
$ sudo cmake .
$ sudo make
$ sudo cp ./googlemock/libgmock.a ./googlemock/gtest/libgtest.a /usr/lib/
# less than 1.18.0
$ cd /usr/src/gtest
$ sudo cmake .
$ sudo make
$ sudo cp libgtest.a /usr/lib
$ cd /usr/src/gmock
$ sudo cmake .
$ sudo make
$ sudo cp libgmock.a /usr/lib
- 在 Pulsar 仓库中编译Pulsar C++ 客户端库。
$ cd pulsar-client-cpp
$ cmake .
$ make
安装组件成功后,文件 libpulsar.so
和 libpulsar.a
位于资源库的 liblib
文件夹中。 工具 famerProducer
and familConsumer
在 perf
目录中。
安装依赖项
Since 2.1.0 release, Pulsar ships pre-built RPM and Debian packages. You can download and install those packages directly.
下载并安装 RPM 或 DEB后, libpulsar.so
, libpulsarnosl.so
, libpulsar.
和 libpulsarwithdeps.a
库位于您的 /usr/lib
目录。
By default, they are built in code path ${PULSAR_HOME}/pulsar-client-cpp
. You can build with the command below.
cmake . -DBUILD_TESTS=OFF -DLINK_STATIC=ON && make pulsarShared pulsarSharedNossl pulsarStatic pulsarStaticWithDeps -j 3
.
这些库依靠其他一些库。 如果您想要获得详细的依赖版本,请参阅 RPM or DEB 文件。
libpulsar.so
是一个共享的库,其中包含静态链接的boost
和openssl
它还动态地连接所有其他必要的库。 您可以使用此Pulsar库下面的命令。
g++ --std=c++11 PulsarTest.cpp -o test /usr/lib/libpulsar.so -I/usr/local/ssl/include
libpulsarnossl.so
是一个共享的库,类似于libpulsar.so
,然而openssl
和crypto
库是动态链接的。 您可以使用此Pulsar库下面的命令。
g++ --std=c++11 PulsarTest.cpp -o test /usr/lib/libpulsarnossl.so -lssl -lcrypto -I/usr/local/ssl/include -L/usr/local/ssl/lib
libpulsar.a
is a static library. You need to load dependencies before using this library. 您可以使用此Pulsar库下面的命令。
g++ --std=c++11 PulsarTest.cpp -o test /usr/lib/libpulsar.a -lssl -lcrypto -ldl -lpthread -I/usr/local/ssl/include -L/usr/local/ssl/lib -lboost_system -lboost_regex -lcurl -lprotobuf -lzstd -lz
libpulsarwithdep.a
是一个静态库,基于libpulsar.a
。 它被归档于libnourt_regex
,libnot_system
,libcurl
,libprotobuf
,libzstd
和libz
. 您可以使用此Pulsar库下面的命令。
g++ --std=c++11 PulsarTest.cpp -o test /usr/lib/libpulsarwithdeps.a -lssl -lcrypto -ldl -lpthread -I/usr/local/ssl/include -L/usr/local/ssl/lib
libpulsarwithdeps.
不包括和 openssl 相关的 libssl
和 libcrypto
库, 因为这两个库与安全有关。 使用本地系统提供的版本来处理安全问题和升级库更加简单合理。
Install RPM
- Download a RPM package from the links in the table.
链接 | 加密文件 |
---|---|
client | asc, sha512 |
client-debuginfo | asc, sha512 |
client-devel | asc, sha512 |
- Install the package using the following command.
$ rpm -ivh apache-pulsar-client*.rpm
安装RPM成功后,Pulsar 库位于 /usr/lib
目录中。
Note
If you get the error thatlibpulsar.so: cannot open shared object file: No such file or directory
when starting Pulsar client, you may need to runldconfig
first.
Install Debian
- Download a Debian package from the links in the table.
链接 | 加密文件 |
---|---|
client | asc, sha512 |
client-devel | asc, sha512 |
- Install the package using the following command.
$ apt install ./apache-pulsar-client*.deb
安装DEB成功后,Pulsar 库位于 /usr/lib
目录中。
编译
If you want to build RPM and Debian packages from the latest master, follow the instructions below. You should run all the instructions at the root directory of your cloned Pulsar repository.
你可以通过下面的方式来编译包含libpulsar.so
/ libpulsar.a
/ libpulsarnossl.so
/ libpulsarwithdeps.a
静态库以及所有必要依赖的二进制包。
要构建C++库包,您需要先构建Java 包。
mvn install -DskipTests
RPM
To build the RPM inside a Docker container, use the command below. The RPMs are in the pulsar-client-cpp/pkg/rpm/RPMS/x86_64/
path.
pulsar-client-cpp/pkg/rpm/docker-build-rpm.sh
包名 | 内容 |
---|---|
pulsar-client | 共享库 libpulsar.so and libpulsarnossl.so |
pulsar-client-devel | 静态库 libpulsar.a , libpulsarwithdeps.a 和 C++ 和 Cheaders |
pulsar-client-debuginfo | Debug symbols for libpulsar.so |
Debian
To build Debian packages, enter the following command.
pulsar-client-cpp/pkg/deb/docker-build-deb.sh
编译好的DEB包会被保存在文件夹 pulsar-client-cpp/pkg/deb/BUILD/DEB/
中.
包名 | 内容 |
---|---|
pulsar-client | 共享库 libpulsar.so and libpulsarnossl.so |
pulsar-client-dev | 静态库 libpulsar.a , libpulsarwithdeps.a 和 C++ 和 Cheaders |
MacOS
编译
- 克隆Pulsar项目仓库
$ git clone https://github.com/apache/pulsar
- 安装所有必要的依赖项。
# OpenSSL installation
$ brew install openssl
$ export OPENSSL_INCLUDE_DIR=/usr/local/opt/openssl/include/
$ export OPENSSL_ROOT_DIR=/usr/local/opt/openssl/
# Protocol Buffers installation
$ brew install protobuf boost boost-python log4cxx
# If you are using python3, you need to install boost-python3
# Google Test installation
$ git clone https://github.com/google/googletest.git
$ cd googletest
$ cmake .
$ make install
- 然后在您克隆的repo中编译Pulsar客户端库:
$ cd pulsar-client-cpp
$ cmake .
$ make
安装 libpulsar
Pulsar releases are available in the Homebrew core repository. You can install the C++ client library with the following command. The package is installed with the library and headers.
brew install libpulsar
Windows (x64)
编译
- 克隆Pulsar项目仓库
$ git clone https://github.com/apache/pulsar
- 安装所有必要的依赖项。
cd ${PULSAR_HOME}/pulsar-client-cpp
vcpkg install --feature-flags=manifests --triplet x64-windows
- 构建 C++ 库。
cmake -B ./build -A x64 -DBUILD_PYTHON_WRAPPER=OFF -DBUILD_TESTS=OFF -DVCPKG_TRIPLET=x64-windows -DCMAKE_BUILD_TYPE=Release -S .
cmake --build ./build --config Release
NOTE
- 对于Windows 32位, 您需要使用
-A Win32
和-DVCPKG_TRIPLET=x86-window
- 对于MSVC 调试模式,您需要将
CMAKE_BUILD_TYPE
变量和--config
选项中的Release
替换为Debug
。
- 客户端库在以下位置。
${PULSAR_HOME}/pulsar-client-cpp/build/lib/Release/pulsar.lib
${PULSAR_HOME}/pulsar-client-cpp/build/lib/Release/pulsar.dll
连接 URL
要使用客户端库连接Pulsar,您需要指定一个 Pulsar 协议 URL。
Pulsar protocol URLs are assigned to specific clusters, you can use the Pulsar URI scheme. The default port is 6650
. The following is an example for localhost.
pulsar://localhost:6650
在一个Pulsar生产集群中,URL如下所示。
pulsar://pulsar.us-west.example.com:6650
If you use TLS authentication, you need to add ssl
, and the default port is 6651
. The following is an example.
pulsar+ssl://pulsar.us-west.example.com:6651
Create a consumer
To use Pulsar as a consumer, you need to create a consumer on the C++ client. There are two main ways of using the consumer:
- Blocking style: synchronously calling
receive(msg)
. - Non-blocking (event based) style: using a message listener.
阻塞示例
The benefit of this approach is that it is the simplest code. Simply keeps calling receive(msg)
which blocks until a message is received.
此示例在最早的偏移量开始订阅并消费100条消息。
#include <pulsar/Client.h>
using namespace pulsar;
int main() {
Client client("pulsar://localhost:6650");
Consumer consumer;
ConsumerConfiguration config;
config.setSubscriptionInitialPosition(InitialPositionEarliest);
Result result = client.subscribe("persistent://public/default/my-topic", "consumer-1", config, consumer);
if (result != ResultOk) {
std::cout << "Failed to subscribe: " << result << std::endl;
return -1;
}
Message msg;
int ctr = 0;
// consume 100 messages
while (ctr < 100) {
consumer.receive(msg);
std::cout << "Received: " << msg
<< " with payload '" << msg.getDataAsString() << "'" << std::endl;
consumer.acknowledge(msg);
ctr++;
}
std::cout << "Finished consuming synchronously!" << std::endl;
client.close();
return 0;
}
消息监听器
你可以不运行循环阻塞方式,而选择调用基于事件的消息监听方式来接收每一条消息。
此示例在最早的偏移量开始订阅并消费100条消息。
#include <pulsar/Client.h>
#include <atomic>
#include <thread>
using namespace pulsar;
std::atomic<uint32_t> messagesReceived;
void handleAckComplete(Result res) {
std::cout << "Ack res: " << res << std::endl;
}
void listener(Consumer consumer, const Message& msg) {
std::cout << "Got message " << msg << " with content '" << msg.getDataAsString() << "'" << std::endl;
messagesReceived++;
consumer.acknowledgeAsync(msg.getMessageId(), handleAckComplete);
}
int main() {
Client client("pulsar://localhost:6650");
Consumer consumer;
ConsumerConfiguration config;
config.setMessageListener(listener);
config.setSubscriptionInitialPosition(InitialPositionEarliest);
Result result = client.subscribe("persistent://public/default/my-topic", "consumer-1", config, consumer);
if (result != ResultOk) {
std::cout << "Failed to subscribe: " << result << std::endl;
return -1;
}
// wait for 100 messages to be consumed
while (messagesReceived < 100) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "Finished consuming asynchronously!" << std::endl;
client.close();
return 0;
}
Create a producer
To use Pulsar as a producer, you need to create a producer on the C++ client. There are two main ways of using a producer:
- Blocking style : each call to
send
waits for an ack from the broker. - Non-blocking asynchronous style :
sendAsync
is called instead ofsend
and a callback is supplied for when the ack is received from the broker.
简单的阻塞示例
This example sends 100 messages using the blocking style. While simple, it does not produce high throughput as it waits for each ack to come back before sending the next message.
#include <pulsar/Client.h>
#include <thread>
using namespace pulsar;
int main() {
Client client("pulsar://localhost:6650");
Result result = client.createProducer("persistent://public/default/my-topic", producer);
if (result != ResultOk) {
std::cout << "Error creating producer: " << result << std::endl;
return -1;
}
// Send 100 messages synchronously
int ctr = 0;
while (ctr < 100) {
std::string content = "msg" + std::to_string(ctr);
Message msg = MessageBuilder().setContent(content).setProperty("x", "1").build();
Result result = producer.send(msg);
if (result != ResultOk) {
std::cout << "The message " << content << " could not be sent, received code: " << result << std::endl;
} else {
std::cout << "The message " << content << " sent successfully" << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
ctr++;
}
std::cout << "Finished producing synchronously!" << std::endl;
client.close();
return 0;
}
非阻塞示例
此示例使用非阻塞方式发送100条消息并使用 sendAsync
代替 send
。 这使得生产者可以并行发送多条消息,从而提高吞吐量。
生产者配置blockIfQueueFull
在这里很有用,可以避免传出发送请求的内部队列已满时出现ResultProducerQueueIsFull
错误。 一旦内部队列已满, sendAsync
就会变成阻塞,使您的代码变得更加简单。
Without this configuration, the result code ResultProducerQueueIsFull
is passed to the callback. You must decide how to deal with that (retry, discard etc).
#include <pulsar/Client.h>
#include <thread>
using namespace pulsar;
std::atomic<uint32_t> acksReceived;
void callback(Result code, const MessageId& msgId, std::string msgContent) {
// message processing logic here
std::cout << "Received ack for msg: " << msgContent << " with code: "
<< code << " -- MsgID: " << msgId << std::endl;
acksReceived++;
}
int main() {
Client client("pulsar://localhost:6650");
ProducerConfiguration producerConf;
producerConf.setBlockIfQueueFull(true);
Producer producer;
Result result = client.createProducer("persistent://public/default/my-topic",
producerConf, producer);
if (result != ResultOk) {
std::cout << "Error creating producer: " << result << std::endl;
return -1;
}
// Send 100 messages asynchronously
int ctr = 0;
while (ctr < 100) {
std::string content = "msg" + std::to_string(ctr);
Message msg = MessageBuilder().setContent(content).setProperty("x", "1").build();
producer.sendAsync(msg, std::bind(callback,
std::placeholders::_1, std::placeholders::_2, content));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
ctr++;
}
// wait for 100 messages to be acked
while (acksReceived < 100) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "Finished producing asynchronously!" << std::endl;
client.close();
return 0;
}
分区主题和懒惰生产者
在扩展 Pulsar 主题时,您可以将主题配置成数百个分区。 同样,您也可以扩展您的生产者,从数百个到数千个生产者。 这可能会给 Pulsar brokers 带来一些压力,因为当你在分区主题上创建生产者时,内部会为每个分区创建一个内部生产者,这涉及到每个分区与 brokers 的通信。 因此,对于一个有1000个分区和1000个生产者的主题,它最终在生产者应用程序之间创建了1,000,000个内部生产者,每个生产者应用程序都必须与 broker 通信,以确定它应该连接到哪个 broker ,然后执行连接握手。
You can reduce the load caused by this combination of a large number of partitions and many producers by doing the following:
- use SinglePartition partition routing mode (this ensures that all messages are only sent to a single, randomly selected partition)
- use non-keyed messages (when messages are keyed, routing is based on the hash of the key and so messages will end up being sent to multiple partitions)
- use lazy producers (this ensures that an internal producer is only created on demand when a message needs to be routed to a partition)
通过我们上面的例子,这将1000个生产者应用程序的内部生产者数量从1000000减少到了1000。
Note that there can be extra latency for the first message sent. If you set a low send timeout, this timeout could be reached if the initial connection handshake is slow to complete.
ProducerConfiguration producerConf;
producerConf.setPartitionsRoutingMode(ProducerConfiguration::UseSinglePartition);
producerConf.setLazyStartPartitionedProducers(true);
Enable authentication in connection URLs
If you use TLS authentication when connecting to Pulsar, you need to add ssl
in the connection URLs, and the default port is 6651
. The following is an example.
ClientConfiguration config = ClientConfiguration();
config.setUseTls(true);
config.setTlsTrustCertsFilePath("/path/to/cacert.pem");
config.setTlsAllowInsecureConnection(false);
config.setAuth(pulsar::AuthTls::create(
"/path/to/client-cert.pem", "/path/to/client-key.pem"););
Client client("pulsar+ssl://my-broker.com:6651", config);
For complete examples, refer to C++ client examples.
Schema
This section describes some examples about schema. For more information about schema, see Pulsar schema.
Avro 模式
The following example shows how to create a producer with an Avro schema.
static const std::string exampleSchema =
"{\"type\":\"record\",\"name\":\"Example\",\"namespace\":\"test\","
"\"fields\":[{\"name\":\"a\",\"type\":\"int\"},{\"name\":\"b\",\"type\":\"int\"}]}";
Producer producer;
ProducerConfiguration producerConf;
producerConf.setSchema(SchemaInfo(AVRO, "Avro", exampleSchema));
client.createProducer("topic-avro", producerConf, producer);
The following example shows how to create a consumer with an Avro schema.
static const std::string exampleSchema =
"{\"type\":\"record\",\"name\":\"Example\",\"namespace\":\"test\","
"\"fields\":[{\"name\":\"a\",\"type\":\"int\"},{\"name\":\"b\",\"type\":\"int\"}]}";
ConsumerConfiguration consumerConf;
Consumer consumer;
consumerConf.setSchema(SchemaInfo(AVRO, "Avro", exampleSchema));
client.subscribe("topic-avro", "sub-2", consumerConf, consumer)
ProtobufNative 模式
The following example shows how to create a producer and a consumer with a ProtobufNative schema.
Generate the
User
class using Protobuf3.Note
You need to use Protobuf3 or later versions. syntax = "proto3";
message User {
string name = 1;
int32 age = 2;
}
Include the
ProtobufNativeSchema.h
in your source code. Ensure the Protobuf dependency has been added to your project. #include <pulsar/ProtobufNativeSchema.h>
Create a producer to send a
User
instance. ProducerConfiguration producerConf;
producerConf.setSchema(createProtobufNativeSchema(User::GetDescriptor()));
Producer producer;
client.createProducer("topic-protobuf", producerConf, producer);
User user;
user.set_name("my-name");
user.set_age(10);
std::string content;
user.SerializeToString(&content);
producer.send(MessageBuilder().setContent(content).build());
Create a consumer to receive a
User
instance. ConsumerConfiguration consumerConf;
consumerConf.setSchema(createProtobufNativeSchema(User::GetDescriptor()));
consumerConf.setSubscriptionInitialPosition(InitialPositionEarliest);
Consumer consumer;
client.subscribe("topic-protobuf", "my-sub", consumerConf, consumer);
Message msg;
consumer.receive(msg);
User user2;
user2.ParseFromArray(msg.getData(), msg.getLength());