lapin-futures
This library offers a futures based API over the lapin-async library.
It leverages the tokio-io and futures library, so you can use it
with tokio, futures-cpupool or any other reactor.
The library is designed so it does not own the socket, so you
can use any TCP, TLS or unix socket based stream.
Calls to the underlying stream are guarded by a mutex, so you could
use one connection from multiple threads.
There's an example available
using tokio.
Publishing a message
#[macro_use] extern crate log;
extern crate lapin_futures as lapin;
extern crate futures;
extern crate tokio;
use futures::future::Future;
use futures::Stream;
use tokio::net::TcpStream;
use tokio::runtime::Runtime;
use lapin::client::ConnectionOptions;
use lapin::channel::{BasicPublishOptions,BasicProperties,QueueDeclareOptions};
use lapin::types::FieldTable;
fn main() {
let addr = "127.0.0.1:5672".parse().unwrap();
Runtime::new().unwrap().block_on(
TcpStream::connect(&addr).and_then(|stream| {
lapin::client::Client::connect(stream, ConnectionOptions::default())
}).and_then(|(client, _ /* heartbeat */)| {
client.create_channel()
}).and_then(|channel| {
let id = channel.id;
info!("created channel with id: {}", id);
channel.queue_declare("hello", QueueDeclareOptions::default(), FieldTable::new()).and_then(move |_| {
info!("channel {} declared queue {}", id, "hello");
channel.basic_publish("", "hello", b"hello from tokio".to_vec(), BasicPublishOptions::default(), BasicProperties::default())
})
})
).expect("runtime exited with error");
}
Creating a consumer
#[macro_use] extern crate log;
extern crate env_logger;
extern crate lapin_futures as lapin;
extern crate futures;
extern crate tokio;
use futures::future::Future;
use futures::Stream;
use tokio::net::TcpStream;
use tokio::runtime::Runtime;
use lapin::client::ConnectionOptions;
use lapin::channel::{BasicConsumeOptions,QueueDeclareOptions};
use lapin::types::FieldTable;
fn main() {
env_logger::init();
let addr = "127.0.0.1:5672".parse().unwrap();
Runtime::new().unwrap().block_on(
TcpStream::connect(&addr).and_then(|stream| {
lapin::client::Client::connect(stream, ConnectionOptions::default())
}).and_then(|(client, heartbeat)| {
tokio::spawn(heartbeat.map_err(|_| ()));
client.create_channel()
}).and_then(|channel| {
let id = channel.id;
info!("created channel with id: {}", id);
let ch = channel.clone();
channel.queue_declare("hello", QueueDeclareOptions::default(), FieldTable::new()).and_then(move |queue| {
info!("channel {} declared queue {}", id, "hello");
channel.basic_consume(&queue, "my_consumer", BasicConsumeOptions::default(), FieldTable::new())
}).and_then(|stream| {
info!("got consumer stream");
stream.for_each(move |message| {
debug!("got message: {:?}", message);
info!("decoded message: {:?}", std::str::from_utf8(&message.data).unwrap());
ch.basic_ack(message.delivery_tag, false)
})
})
})
).expect("runtime exited with error");
}