本页尚未翻译
下面显示的是英文原文。
One filter mounted twice
Two handlers on one filter are one subscription on the server, so they take the messages in turn.
A server holds one subscription per filter, and subscribing the same filter again replaces it. So the subscriptions an app opens on one filter are members of one route: they share its deliveries, and each message reaches one of them, the next in order. The members of a share group work the same way. A handler that must see every message reads a filter of its own.
Example
Two handlers on jobs/+: the first takes the first message, the second takes the next, and so on.
- Macros
- Manual
/// The first of two handlers on the same filter.
#[subscriber(MqttFilter::new("jobs/+"))]
async fn first(job: &Job) -> HandlerOutcome {
let _ = job.id;
HandlerOutcome::ack()
}
/// The second takes every other message the filter matches.
#[subscriber(MqttFilter::new("jobs/+"))]
async fn second(job: &Job) -> HandlerOutcome {
let _ = job.id;
HandlerOutcome::ack()
}
#[ruststream::app(runtime = embassy)]
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| b.include(first).include(second))
}
/// The first of two handlers on the same filter.
struct First;
impl Handle<Job> for First {
fn handle(
&self,
_job: &Job,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
ready(Ok(()))
}
}
/// The second takes every other message the filter matches.
struct Second;
impl Handle<Job> for Second {
fn handle(
&self,
_job: &Job,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
ready(Ok(()))
}
}
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
b.include(
subscriber("jobs/+", First)
.map_source(|_| MqttFilter::new("jobs/+"))
.build(),
)
.include(
subscriber("jobs/+", Second)
.map_source(|_| MqttFilter::new("jobs/+"))
.build(),
)
})
}