Struct nats::Connection

source ·
pub struct Connection(/* private fields */);
Expand description

A NATS connection.

Implementations§

source§

impl Connection

source

pub fn subscribe(&self, subject: &str) -> Result<Subscription>

Create a subscription for the given NATS connection.

§Example
let sub = nc.subscribe("foo")?;
source

pub fn queue_subscribe( &self, subject: &str, queue: &str ) -> Result<Subscription>

Create a queue subscription for the given NATS connection.

§Example
let sub = nc.queue_subscribe("foo", "production")?;
source

pub fn publish(&self, subject: &str, msg: impl AsRef<[u8]>) -> Result<()>

Publish a message on the given subject.

§Example
nc.publish("foo", "Hello World!")?;
source

pub fn publish_request( &self, subject: &str, reply: &str, msg: impl AsRef<[u8]> ) -> Result<()>

Publish a message on the given subject with a reply subject for responses.

§Example
let reply = nc.new_inbox();
let rsub = nc.subscribe(&reply)?;
nc.publish_request("foo", &reply, "Help me!")?;
source

pub fn new_inbox(&self) -> String

Create a new globally unique inbox which can be used for replies.

§Example
let reply = nc.new_inbox();
let rsub = nc.subscribe(&reply)?;
source

pub fn request(&self, subject: &str, msg: impl AsRef<[u8]>) -> Result<Message>

Publish a message on the given subject as a request and receive the response.

§Example
let resp = nc.request("foo", "Help me?")?;
source

pub fn request_timeout( &self, subject: &str, msg: impl AsRef<[u8]>, timeout: Duration ) -> Result<Message>

Publish a message on the given subject as a request and receive the response. This call will return after the timeout duration if no response is received.

§Example
let resp = nc.request_timeout("foo", "Help me?", std::time::Duration::from_secs(2))?;
source

pub fn request_with_headers( &self, subject: &str, msg: impl AsRef<[u8]>, headers: &HeaderMap ) -> Result<Message>

Publish a message with headers on the given subject as a request and receive the response.

§Example
let mut headers = nats::HeaderMap::new();
headers.insert("X-key", "value".to_string());
let resp = nc.request_with_headers_or_timeout(
    "foo",
    Some(&headers),
    Some(std::time::Duration::from_secs(2)),
    "Help me?",
)?;
source

pub fn request_with_headers_or_timeout( &self, subject: &str, maybe_headers: Option<&HeaderMap>, maybe_timeout: Option<Duration>, msg: impl AsRef<[u8]> ) -> Result<Message>

Publish a message on the given subject as a request and receive the response. This call will return after the timeout duration if it was set to Some if no response is received. It also allows passing headers.

§Example
let mut headers = nats::HeaderMap::new();
headers.insert("X-key", "value".to_string());
let resp = nc.request_with_headers_or_timeout(
    "foo",
    Some(&headers),
    Some(std::time::Duration::from_secs(2)),
    "Help me?",
)?;
source

pub fn request_multi( &self, subject: &str, msg: impl AsRef<[u8]> ) -> Result<Subscription>

Publish a message on the given subject as a request and allow multiple responses.

§Example
for msg in nc.request_multi("foo", "Help")?.iter().take(1) {}
source

pub fn flush(&self) -> Result<()>

Flush a NATS connection by sending a PING protocol and waiting for the responding PONG. Will fail with TimedOut if the server does not respond with in 10 seconds. Will fail with NotConnected if the server is not currently connected. Will fail with BrokenPipe if the connection to the server is lost.

§Example
nc.flush()?;
source

pub fn flush_timeout(&self, duration: Duration) -> Result<()>

Flush a NATS connection by sending a PING protocol and waiting for the responding PONG. Will fail with TimedOut if the server takes longer than this duration to respond. Will fail with NotConnected if the server is not currently connected. Will fail with BrokenPipe if the connection to the server is lost.

§Example
nc.flush_timeout(Duration::from_secs(5))?;
source

pub fn close(self)

Close a NATS connection. All clones of this Connection will also be closed, as the backing IO threads are shared.

If the client is currently connected to a server, the outbound write buffer will be flushed in the process of shutting down.

§Example
nc.close();
source

pub fn rtt(&self) -> Result<Duration>

Calculates the round trip time between this client and the server, if the server is currently connected. Fails with TimedOut if the server takes more than 10 seconds to respond.

§Example
println!("server rtt: {:?}", nc.rtt());
source

pub fn is_server_compatible_version( &self, major: i64, minor: i64, patch: i64 ) -> bool

Returns true if the version is compatible with the version components.

source

pub fn client_ip(&self) -> Result<IpAddr>

Returns the client IP as known by the server. Supported as of server version 2.1.6.

§Example
println!("ip: {:?}", nc.client_ip());
source

pub fn client_id(&self) -> u64

Returns the client ID as known by the most recently connected server.

§Example
println!("ip: {:?}", nc.client_id());
source

pub fn drain(&self) -> Result<()>

Send an unsubscription for all subs then flush the connection, allowing any unprocessed messages to be handled by a handler function if one is configured.

After the flush returns, we know that a round-trip to the server has happened after it received our unsubscription, so we shut down the subscriber afterwards.

A similar method exists for the Subscription struct which will drain a single Subscription without shutting down the entire connection afterward.

§Example
let received = Arc::new(AtomicBool::new(false));
let received_2 = received.clone();

nc.subscribe("test.drain")?.with_handler(move |m| {
    received_2.store(true, SeqCst);
    Ok(())
});

nc.publish("test.drain", "message")?;
nc.drain()?;


assert!(received.load(SeqCst));
source

pub fn publish_with_reply_or_headers( &self, subject: &str, reply: Option<&str>, headers: Option<&HeaderMap>, msg: impl AsRef<[u8]> ) -> Result<()>

Publish a message which may have a reply subject or headers set.

§Example
let sub = nc.subscribe("foo.headers")?;
let headers = [("header1", "value1"), ("header2", "value2")]
    .iter()
    .collect();
let reply_to = None;
nc.publish_with_reply_or_headers("foo.headers", reply_to, Some(&headers), "Hello World!")?;
nc.flush()?;
let message = sub.next_timeout(std::time::Duration::from_secs(2)).unwrap();
assert_eq!(message.headers.unwrap().len(), 2);
source

pub fn max_payload(&self) -> usize

Returns the maximum payload size the most recently connected server will accept.

§Example
let nc = nats::connect("demo.nats.io")?;
println!("max payload: {:?}", nc.max_payload());

Trait Implementations§

source§

impl Clone for Connection

source§

fn clone(&self) -> Connection

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Connection

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more