kafka c++ 库
时间: 2023-07-07 15:39:44 浏览: 130
libkafka:适用于Apache Kafka v0.8 +的C ++客户端库。 还包括C API
Kafka C++库是用于构建Kafka客户端的C++库。以下是一些常用的Kafka C++库:
1. librdkafka++:是librdkafka库的C++封装,提供了一个易于使用的Kafka客户端API。
2. rdkafka++:是另一个librdkafka库的C++封装,提供了一个简单的Kafka客户端API。
3. cppkafka:是一个纯C++库,提供了一个高级的Kafka客户端API,支持同步和异步消息处理。
使用Kafka C++库的基本步骤与使用librdkafka库相似。以下是使用librdkafka++库的示例代码:
```c++
#include <iostream>
#include <string>
#include <librdkafka/rdkafkacpp.h>
int main() {
std::string brokers = "localhost:9092";
std::string topic = "test_topic";
RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
conf->set("bootstrap.servers", brokers, errstr);
RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr);
if (!producer) {
std::cerr << "Failed to create producer: " << errstr << std::endl;
delete conf;
return 1;
}
RdKafka::Topic *rkt = RdKafka::Topic::create(producer, topic, NULL, errstr);
if (!rkt) {
std::cerr << "Failed to create topic: " << errstr << std::endl;
delete producer;
delete conf;
return 1;
}
std::string message = "Hello, Kafka!";
RdKafka::ErrorCode resp = producer->produce(rkt, RD_KAFKA_PARTITION_UA, RD_KAFKA_MSG_F_COPY, const_cast<char *>(message.c_str()), message.size(), NULL, 0, 0, NULL);
if (resp != RdKafka::ERR_NO_ERROR) {
std::cerr << "Failed to produce message: " << RdKafka::err2str(resp) << std::endl;
}
producer->flush(5000);
delete rkt;
delete producer;
delete conf;
return 0;
}
```
这是一个使用librdkafka++库的简单Kafka生产者示例代码,它将消息“Hello, Kafka!”发送到Kafka集群。您可以使用类似的方式创建Kafka消费者。
阅读全文