-
Notifications
You must be signed in to change notification settings - Fork 121
/
consumer.rs
89 lines (74 loc) · 2.55 KB
/
consumer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#[macro_use]
extern crate serde;
use std::env;
use futures::TryStreamExt;
use pulsar::{
authentication::oauth2::OAuth2Authentication, Authentication, Consumer, DeserializeMessage,
Payload, Pulsar, SubType, TokioExecutor,
};
#[derive(Serialize, Deserialize)]
struct TestData {
data: String,
}
impl DeserializeMessage for TestData {
type Output = Result<TestData, serde_json::Error>;
fn deserialize_message(payload: &Payload) -> Self::Output {
serde_json::from_slice(&payload.data)
}
}
#[tokio::main]
async fn main() -> Result<(), pulsar::Error> {
env_logger::init();
let addr = env::var("PULSAR_ADDRESS")
.ok()
.unwrap_or_else(|| "pulsar://127.0.0.1:6650".to_string());
let topic = env::var("PULSAR_TOPIC")
.ok()
.unwrap_or_else(|| "non-persistent://public/default/test".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") {
builder = builder.with_auth_provider(OAuth2Authentication::client_credentials(
serde_json::from_str(oauth2_cfg.as_str())
.unwrap_or_else(|_| panic!("invalid oauth2 config [{}]", oauth2_cfg.as_str())),
));
}
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? {
consumer.ack(&msg).await?;
log::info!("metadata: {:?}", msg.metadata());
log::info!("id: {:?}", msg.message_id());
let data = match msg.deserialize() {
Ok(data) => data,
Err(e) => {
log::error!("could not deserialize message: {:?}", e);
break;
}
};
if data.data.as_str() != "data" {
log::error!("Unexpected payload: {}", &data.data);
break;
}
counter += 1;
log::info!("got {} messages", counter);
if counter > 10 {
consumer.close().await.expect("Unable to close consumer");
break;
}
}
Ok(())
}