Ниже показан английский оригинал.
last_will
last_will names the message the server publishes when the connection ends without a clean disconnect, such as a service's offline status.
The will travels in the CONNECT packet, and the server keeps it for as long as the connection lasts.
It has a topic, a payload, a QoS and a retain flag, like any publish.
The payload is bytes, written as the service's readers decode them; no codec runs on it.
The server publishes the will when the connection ends any other way than by the client's DISCONNECT.
That covers a process that dies, a network that drops, a connection silent past its keep-alive, and a second client that takes the client id over.
A clean shutdown sends a DISCONNECT, and the server discards the will.
A retained will stays on its topic, so a dashboard that subscribes later still reads that the service is gone.
The server publishes the will, so a TestApp test in process runs the app without it.
A live test shows it.
The generated AsyncAPI document reports the will's topic, QoS and retain flag, not its payload.
Example
Each instance announces its own death on services/<client id>/status, retained.
- Macros
- Manual
/// If the connection ends without a clean disconnect, the server publishes `{"online":false}`
/// on the service's status topic and keeps it there for every later subscriber.
fn broker(url: &str, client_id: &str) -> MqttBroker {
MqttBroker::new(url, client_id).last_will(
format!("services/{client_id}/status"),
r#"{"online":false}"#,
Qos::AtLeastOnce,
true,
)
}
#[ruststream::app]
fn app() -> impl App<State = ()> {
service(broker("mqtt://localhost:1883", "telemetry-svc"))
}
/// If the connection ends without a clean disconnect, the server publishes `{"online":false}`
/// on the service's status topic and keeps it there for every later subscriber.
fn broker(url: &str, client_id: &str) -> MqttBroker {
MqttBroker::new(url, client_id).last_will(
format!("services/{client_id}/status"),
r#"{"online":false}"#,
Qos::AtLeastOnce,
true,
)
}
fn app() -> impl App<State = ()> {
service(broker("mqtt://localhost:1883", "telemetry-svc"))
}