// The client configuration information.ClientConfiguration config;// Set the authorized role token.AuthenticationPtr auth = pulsar::AuthToken::createWithToken(AUTHENTICATION);config.setAuth(auth);// Create a client.Client client(SERVICE_URL, config);
Parameter | Description |
SERVICE_URL | Address used to access the cluster. You can view and copy the address from the Cluster page in the console. |
AUTHENTICATION |
// The producer configuration.ProducerConfiguration producerConf;producerConf.setBlockIfQueueFull(true);producerConf.setSendTimeout(5000);// The producer.Producer producer;// Create a producer.Result result = client.createProducer(// The full topic path in the format of persistent://cluster (tenant) ID/namespace/topic."persistent://pulsar-xxx/sdk_cpp/topic1",producerConf,producer);if (result != ResultOk) {std::cout << "Error creating producer: " << result << std::endl;return -1;}
persistent://clusterid/namespace/topic. You can copy the clusterid/namespace/topic part from the Topic page in the console.// The message content.std::string content = "hello cpp client, this is a msg";// Construct a message object.Message msg = MessageBuilder().setContent(content).setPartitionKey("mykey") // The business key..setProperty("x", "1") // Set message parameters..build();// Send a message.Result result = producer.send(msg);if (result != ResultOk) {// Sending fails.std::cout << "The message " << content << " could not be sent, received code: " << result << std::endl;} else {// Sending succeeded.std::cout << "The message " << content << " sent successfully" << std::endl;}
// The consumer configuration information.ConsumerConfiguration consumerConfiguration;consumerConfiguration.setSubscriptionInitialPosition(pulsar::InitialPositionEarliest);// The consumer.Consumer consumer;// Subscribe to a topic.Result result = client.subscribe(// The full topic path in the format of persistent://cluster (tenant) ID/namespace/topic."persistent://pulsar-xxx/sdk_cpp/topic1",// The subscription name."sub_topic1",consumerConfiguration,consumer);if (result != ResultOk) {std::cout << "Failed to subscribe: " << result << std::endl;return -1;}
persistent://clusterid/namespace/topic. You can copy the clusterid/namespace/topic part from the Topic page in the console.
Message msg;// Obtain messages.consumer.receive(msg);// Simulate the business logic.std::cout << "Received: " << msg << " with payload '" << msg.getDataAsString() << "'" << std::endl;// Reply ack.consumer.acknowledge(msg);// If the consumption fails, reply nack and the message will be redelivered.// consumer.negativeAcknowledge(msg);

Feedback