amq-rpc
Lightweight RPC library for RabbitMQ in Rust.
Features
- Async API based on tokio
- JSON serialization support
- Automatic command routing
- Client request timeouts
- Simple and intuitive API
Installation
Add to your Cargo.toml:
[dependencies]
amq-rpc = "0.1.0"
Quick Start
Server
use serde_json::Value;
use async_trait::async_trait;
use amq_rpc::{AmqpConnection, RpcServer, CommandHandler, RpcResult};
struct MathHandler;
#[async_trait]
impl CommandHandler for MathHandler {
async fn handle(&self, command: &str, args: Vec<Value>) -> RpcResult<Value> {
match command {
"add" => {
let a = args[0].as_f64().unwrap_or(0.0);
let b = args[1].as_f64().unwrap_or(0.0);
Ok(Value::Number(serde_json::Number::from_f64(a + b).unwrap()))
}
_ => Err(amq_rpc::RpcError::InvalidCommand {
message: format!("Unknown command: {}", command),
}),
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let connection = AmqpConnection::new("amqp://guest:guest@localhost:5672");
let server = RpcServer::new(connection, "math_queue".to_string());
server.register_handler("add", MathHandler).await;
server.start().await?;
tokio::signal::ctrl_c().await?;
server.close().await?;
Ok(())
}
Client
use serde_json::json;
use amq_rpc::{AmqpConnection, RpcClient};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let connection = AmqpConnection::new("amqp://guest:guest@localhost:5672");
let client = RpcClient::new(connection, Some(30000));
client.start().await?;
let result = client.send_command(
"math_queue",
"add",
vec![json!(5), json!(3)]
).await?;
println!("Result: {}", result);
client.close().await?;
Ok(())
}
Examples
Full examples are available in the examples/ directory:
examples/server.rs - RPC server example
examples/client.rs - RPC client example
License
MIT