This is a small example of using Redis as the persistence store for the Paho MQTT Rust client.
It is an add-on library for use with the Eclipse Paho Rust MQTT Client https://github.com/eclipse/paho.mqtt.rust
The MQTT client library provides several mechanisms to persist QoS 1 & 2 messages while they are in transit. This helps to ensure that even if the client application crashes, upon restart those messages can be retrieved from the persistence store and re-sent to the server.
The Paho library contains file/disk based persistence out of the box. That is very useful, but on a Flash-based Embedded device, like an IoT gateway, but continuous writes to the flash chip will wear it out prematurely.
So it would be nice to use a RAM-based cache that is outside the client application's process. An instance of Redis, running locally, is a nice solution.
The Paho library allows the application to create a user-supplied
persistence object and register that with the client. The object simply
needs to implement the
paho_mqtt::ClientPersistence trait. These
callbacks map to the operations on a key/value store, so Redis is a
perfect candidate to match the persistence API and act as a store.
The MQTT callbacks map nearly 1:1 to Redis Hash commands: open() -> conect close() -> disconnect
put() -> HSET get() -> HGET remove() -> HDEL keys() -> HKEYS clear() -> DEL contains_key() -> HEXISTS
NOTE: Using Redis as an MQTT persistence store is an extremely viable solution in a production IoT device or gateway, but it really only makes sense to use it if the Redis server is running locally on the device and connected via localhost or a UNIX socket. It does not make sense to use a remote Redis server for this purpose.
The MQTT Redis persistence object. An instance of this stuct can be residtered with an MQTT client to hold messgaes in a Redis server until they are properly acknowledged by the remote MQTT server. An instance of this object maps to a single hash on a specific Redis server.