Reputation: 69
Is there any canonical way in Rust to publish a frequently updating ‘state’ such that any number of consumers can read it without providing access to the object itself?
My use case is that I have a stream of information coming in via web socket and wish to have aggregated metrics available to consume by other threads. One could do this externally with something like Kafka, and I could probably roll my own internal solution but wondering if there is any other method?
An alternative which I’ve used in Go is to have consumers register themselves with the producer and each receive a channel, with the producer simply publishing to each channel separately. There will generally be a low number of consumers so this may well work, but wondering if there’s anything better.
Upvotes: 2
Views: 184
Reputation: 60822
It sounds like you want a "broadcast channel".
If you're using async
, the popular tokio
crate provides an implementation in their sync::broadcast
module:
A multi-producer, multi-consumer broadcast queue. Each sent value is seen by all consumers.
A
Sender
is used to broadcast values to all connectedReceiver
values.Sender
handles are clone-able, allowing concurrent send and receive actions. [...][...]
New
Receiver
handles are created by callingSender::subscribe
. The returnedReceiver
will receive values sent after the call tosubscribe
.
If that doesn't quite suit your fancy, there are other crates that provide similar types that can be found by searching for "broadcast" on crates.io.
Upvotes: 3