Crates.io | unisub |
lib.rs | unisub |
version | 0.1.2 |
source | src |
created_at | 2023-10-03 04:45:18.352977 |
updated_at | 2023-10-03 05:01:49.04683 |
description | A Pub/Sub library for Rust backed by Postgres |
homepage | https://nrempel.com |
repository | https://github.com/nrempel/unisub |
max_upload_size | |
id | 990723 |
size | 63,582 |
Unisub is a Pub/Sub library for Rust, using Postgres as the backend. It offers a convenient way to publish and subscribe to messages across different topics.
Add Unisub as a dependency in your Cargo.toml
:
[dependencies]
unisub = "*"
Set an environment variable called DATABASE_URL
with the Postgres connection URL.
export DATABASE_URL=postgres://username:password@localhost/dbname
First, run the migrations:
unisub migrate
Then you can add your topics:
unisub add-topic my_topic
use unisub::PubSub;
use unisub::migrate;
use sqlx::PgPool;
#[tokio::main]
async fn main() -> Result<(), unisub::Error> {
let pool = PgPool::connect("your_database_url").await?;
migrate(&pool).await?;
let mut pubsub = PubSub::new(pool).await?;
pubsub.add_topic("my_topic").await?;
Ok(())
}
use unisub::PubSub;
use sqlx::PgPool;
#[tokio::main]
async fn main() -> Result<(), unisub::Error> {
let pool = PgPool::connect("your_database_url").await?;
let mut pubsub = PubSub::new(pool).await?;
pubsub.push("my_topic", b"My message").await?;
Ok(())
}
And here's an example of how to subscribe to a topic:
use unisub::PubSub;
use sqlx::PgPool;
#[tokio::main]
async fn main() -> Result<(), unisub::Error> {
// Connect to the database
let pool = PgPool::connect("your_database_url").await?;
let mut pubsub = PubSub::new(pool).await?;
// Subscribe to the topic
pubsub.subscribe("my_topic", |message| {
async {
// Print the received message
println!("Received message: {:?}", message);
// Simulate some asynchronous work with the received message
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
println!("Finished processing message: {:?}", message);
Ok(())
}
}).await?;
Ok(())
}
Contributions are welcome! Please submit a pull request or create an issue to get started.
This project is licensed under the MIT License.