Gia Long
03/24/2025, 4:42 AMpulsar-rs library. However, I noticed that it is consuming messages sequentially. I am following the example from the library, but I would like to make it process messages asynchronously. Do you know how to achieve this? Please help me. Here is my Rust code:
#[tokio::main]
async fn main() -> Result<(), pulsar::Error> {
env_logger::init();
let addr = env::var("PULSAR_ADDRESS")
.unwrap_or_else(|_| "pulsar://127.0.0.1:6650".to_string());
let topic = env::var("PULSAR_TOPIC")
.unwrap_or_else(|_| "persistent://public/default/rs".to_string());
let mut builder = Pulsar::builder(addr, TokioExecutor);
if let Ok(token) = env::var("PULSAR_TOKEN") {
let authentication = Authentication {
name: "token".to_string(),
data: token.into_bytes(),
};
builder = builder.with_auth(authentication);
} else if let Ok(oauth2_cfg) = env::var("PULSAR_OAUTH2") {
match serde_json::from_str(oauth2_cfg.as_str()) {
Ok(oauth2_config) => {
builder = builder.with_auth_provider(OAuth2Authentication::client_credentials(oauth2_config));
}
Err(_) => {
log::error!("Invalid OAuth2 config: [{}]", oauth2_cfg.as_str());
return Err(pulsar::Error::Custom("Invalid OAuth2 config".to_string()));
}
}
}
let pulsar: Pulsar<_> = builder.build().await?;
let mut consumer: Consumer<TestData, _> = pulsar
.consumer()
.with_topic(topic)
.with_consumer_name("test_consumer")
.with_subscription_type(SubType::Exclusive)
.with_subscription("test_subscription")
.build()
.await?;
let mut counter = 0usize;
while let Some(msg) = consumer.try_next().await? {
println!("Raw payload: {:?}", String::from_utf8_lossy(&msg.payload.data));
tokio::time::sleep(Duration::from_secs(2)).await;
consumer.ack(&msg).await?;
log::info!("metadata: {:?}", msg.metadata());
log::info!("id: {:?}", msg.message_id());
}
Ok(())
}