[−][src]Crate hive_pubsub
Example
use hive_pubsub::{Hive, PubSub}; let mut hive = Hive::new( |users, data| { println!("Received data! [{:?}]: {}.", users, data); } ); hive.subscribe_multiple(1, vec! [ 2, 5 ]).unwrap(); hive.subscribe_multiple(3, vec! [ 2, 6 ]).unwrap(); hive.subscribe_multiple(4, vec! [ 2, 5 ]).unwrap(); hive.drop_topic(&6).unwrap(); hive.publish(&6, "This will not appear.".to_string()).unwrap(); hive.publish(&2, "This will appear for all three clients.".to_string()).unwrap(); hive.drop_client(&3).unwrap(); hive.publish(&2, "This will appear for two of the clients.".to_string()).unwrap(); hive.publish(&5, "This will also appear for two of the clients.".to_string()).unwrap();
Example, for use with MongoDB.
This example only works with MongoDB and the sync feature enabled. This is for compatibilty reasons down the line, feel free to fork and change a few links to add async compat.
use std::env::var; use mongodb::sync::Client; use std::sync::mpsc::channel; use hive_pubsub::{PubSub}; use hive_pubsub::backend::mongo::{MongodbPubSub, listen_thread}; // You'll want to have some sort of worker which can // handle incoming messages and deal with them accordingly. // Here we are just using a channel with predictable data // so we can just use assert_eq!(). let ( sender, receiver ) = channel(); let client = Client::with_uri_str("mongodb+srv://example.com").unwrap(); let mut hive = MongodbPubSub::<i32, i32, String>::new( move |_ids, data| { // We just send the data into the channel. sender.send(data).unwrap(); }, client.database("hive").collection("pubsub") ); // We need to subscribe to the topic to get any data. hive.subscribe(0, 0).unwrap(); // This is a helper function which spawns a new thread // and starts listening, it simply calls hive.listen() // in a loop { }. It is recommended you use your own // implementation for better error handling, although // any errors will be logged. listen_thread(hive.clone()); // We are setting source here to make the hive instance // accept incoming data. Since `source` is just a String, // it means we just cloned the original value above and // are now replacing it. hive.set_source("1234".to_string()); // Hence, we publish our data. hive.publish(&0, "My data.".to_string()).unwrap(); // And we should receive it back twice. assert_eq!(receiver.recv().unwrap(), "My data."); assert_eq!(receiver.recv().unwrap(), "My data.");
Design
Hive is designed to be slotted into any server application to act as a middle-man between you and your clients, it will automatically distribute any notifications you give it to all relevant connected clients and other nodes.
Modules
backend |
Structs
Hive | The pubsub client. |
Traits
PubSub | PubSub trait which provides common actions. |