async_nats::client

Struct Client

source
pub struct Client { /* private fields */ }
Expand description

Client is a Cloneable handle to NATS connection. Client should not be created directly. Instead, one of two methods can be used: crate::connect and crate::ConnectOptions::connect

Implementations§

source§

impl Client

source

pub fn server_info(&self) -> ServerInfo

Returns last received info from the server.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
println!("info: {:?}", client.server_info());
source

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

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

This has to be used with caution, as it is not guaranteed that the server that client is connected to is the same version that the one that is a JetStream meta/stream/consumer leader, especially across leafnodes.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
assert!(client.is_server_compatible(2, 8, 4));
source

pub async fn publish<S: ToSubject>( &self, subject: S, payload: Bytes, ) -> Result<(), PublishError>

Publish a Message to a given subject.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
client.publish("events.data", "payload".into()).await?;
source

pub async fn publish_with_headers<S: ToSubject>( &self, subject: S, headers: HeaderMap, payload: Bytes, ) -> Result<(), PublishError>

Publish a Message with headers to a given subject.

§Examples
use std::str::FromStr;
let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
headers.insert(
    "X-Header",
    async_nats::HeaderValue::from_str("Value").unwrap(),
);
client
    .publish_with_headers("events.data", headers, "payload".into())
    .await?;
source

pub async fn publish_with_reply<S: ToSubject, R: ToSubject>( &self, subject: S, reply: R, payload: Bytes, ) -> Result<(), PublishError>

Publish a Message to a given subject, with specified response subject to which the subscriber can respond. This method does not await for the response.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
client
    .publish_with_reply("events.data", "reply_subject", "payload".into())
    .await?;
source

pub async fn publish_with_reply_and_headers<S: ToSubject, R: ToSubject>( &self, subject: S, reply: R, headers: HeaderMap, payload: Bytes, ) -> Result<(), PublishError>

Publish a Message to a given subject with headers and specified response subject to which the subscriber can respond. This method does not await for the response.

§Examples
use std::str::FromStr;
let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
client
    .publish_with_reply_and_headers("events.data", "reply_subject", headers, "payload".into())
    .await?;
source

pub async fn request<S: ToSubject>( &self, subject: S, payload: Bytes, ) -> Result<Message, RequestError>

Sends the request with headers.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
let response = client.request("service", "data".into()).await?;
source

pub async fn request_with_headers<S: ToSubject>( &self, subject: S, headers: HeaderMap, payload: Bytes, ) -> Result<Message, RequestError>

Sends the request with headers.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
headers.insert("Key", "Value");
let response = client
    .request_with_headers("service", headers, "data".into())
    .await?;
source

pub async fn send_request<S: ToSubject>( &self, subject: S, request: Request, ) -> Result<Message, RequestError>

Sends the request created by the Request.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
let request = async_nats::Request::new().payload("data".into());
let response = client.send_request("service", request).await?;
source

pub fn new_inbox(&self) -> String

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

§Examples
let reply = nc.new_inbox();
let rsub = nc.subscribe(reply).await?;
source

pub async fn subscribe<S: ToSubject>( &self, subject: S, ) -> Result<Subscriber, SubscribeError>

Subscribes to a subject to receive messages.

§Examples
use futures::StreamExt;
let client = async_nats::connect("demo.nats.io").await?;
let mut subscription = client.subscribe("events.>").await?;
while let Some(message) = subscription.next().await {
    println!("received message: {:?}", message);
}
source

pub async fn queue_subscribe<S: ToSubject>( &self, subject: S, queue_group: String, ) -> Result<Subscriber, SubscribeError>

Subscribes to a subject with a queue group to receive messages.

§Examples
use futures::StreamExt;
let client = async_nats::connect("demo.nats.io").await?;
let mut subscription = client.queue_subscribe("events.>", "queue".into()).await?;
while let Some(message) = subscription.next().await {
    println!("received message: {:?}", message);
}
source

pub async fn flush(&self) -> Result<(), FlushError>

Flushes the internal buffer ensuring that all messages are sent.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
client.flush().await?;
source

pub fn connection_state(&self) -> State

Returns the current state of the connection.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
println!("connection state: {}", client.connection_state());
source

pub async fn force_reconnect(&self) -> Result<(), ReconnectError>

Forces the client to reconnect. Keep in mind that client will reconnect automatically if the connection is lost and this method does not have to be used in normal circumstances. However, if you want to force the client to reconnect, for example to re-trigger the auth-callback, or manually rebalance connections, this method can be useful. This method does not wait for connection to be re-established.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
client.force_reconnect().await?;
source

pub fn statistics(&self) -> Arc<Statistics>

Returns struct representing statistics of the whole lifecycle of the client. This includes number of bytes sent/received, number of messages sent/received, and number of times the connection was established. As this returns Arc with AtomicU64 fields, it can be safely reused and shared across threads.

§Examples
let client = async_nats::connect("demo.nats.io").await?;
let statistics = client.statistics();
println!("client statistics: {:#?}", statistics);

Trait Implementations§

source§

impl Clone for Client

source§

fn clone(&self) -> Client

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

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

Performs copy-assignment from source. Read more
source§

impl Debug for Client

source§

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

Formats the value using the given formatter. Read more
source§

impl ServiceExt for Client

Available on crate feature service only.
source§

type Output = Pin<Box<dyn Future<Output = Result<Service, Box<dyn Error + Sync + Send>>> + Send>>

source§

fn add_service(&self, config: Config) -> Self::Output

Adds a Service instance. Read more
source§

fn service_builder(&self) -> ServiceBuilder

Returns Service instance builder. Read more
source§

impl Sink<PublishMessage> for Client

source§

type Error = Error<PublishErrorKind>

The type of value produced by the sink when an error occurs.
source§

fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Attempts to prepare the Sink to receive a value. Read more
source§

fn start_send( self: Pin<&mut Self>, msg: PublishMessage, ) -> Result<(), Self::Error>

Begin the process of sending a value to the sink. Each call to this function must be preceded by a successful call to poll_ready which returned Poll::Ready(Ok(())). Read more
source§

fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Flush any remaining output from this sink. Read more
source§

fn poll_close( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Flush any remaining output and close this sink, if necessary. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

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> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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

source§

type Output = T

Should always be Self
source§

impl<T, Item> SinkExt<Item> for T
where T: Sink<Item> + ?Sized,

source§

fn with<U, Fut, F, E>(self, f: F) -> With<Self, Item, U, Fut, F>
where F: FnMut(U) -> Fut, Fut: Future<Output = Result<Item, E>>, E: From<Self::Error>, Self: Sized,

Composes a function in front of the sink. Read more
source§

fn with_flat_map<U, St, F>(self, f: F) -> WithFlatMap<Self, Item, U, St, F>
where F: FnMut(U) -> St, St: Stream<Item = Result<Item, Self::Error>>, Self: Sized,

Composes a function in front of the sink. Read more
source§

fn sink_map_err<E, F>(self, f: F) -> SinkMapErr<Self, F>
where F: FnOnce(Self::Error) -> E, Self: Sized,

Transforms the error returned by the sink.
source§

fn sink_err_into<E>(self) -> SinkErrInto<Self, Item, E>
where Self: Sized, Self::Error: Into<E>,

Map this sink’s error to a different error type using the Into trait. Read more
source§

fn buffer(self, capacity: usize) -> Buffer<Self, Item>
where Self: Sized,

Available on crate feature alloc only.
Adds a fixed-size buffer to the current sink. Read more
source§

fn close(&mut self) -> Close<'_, Self, Item>
where Self: Unpin,

Close the sink.
source§

fn fanout<Si>(self, other: Si) -> Fanout<Self, Si>
where Self: Sized, Item: Clone, Si: Sink<Item, Error = Self::Error>,

Fanout items to multiple sinks. Read more
source§

fn flush(&mut self) -> Flush<'_, Self, Item>
where Self: Unpin,

Flush the sink, processing all pending items. Read more
source§

fn send(&mut self, item: Item) -> Send<'_, Self, Item>
where Self: Unpin,

A future that completes after the given item has been fully processed into the sink, including flushing. Read more
source§

fn feed(&mut self, item: Item) -> Feed<'_, Self, Item>
where Self: Unpin,

A future that completes after the given item has been received by the sink. Read more
source§

fn send_all<'a, St>(&'a mut self, stream: &'a mut St) -> SendAll<'a, Self, St>
where St: TryStream<Ok = Item, Error = Self::Error> + Stream + Unpin + ?Sized, Self: Unpin,

A future that completes after the given stream has been fully processed into the sink, including flushing. Read more
source§

fn left_sink<Si2>(self) -> Either<Self, Si2>
where Si2: Sink<Item, Error = Self::Error>, Self: Sized,

Wrap this sink in an Either sink, making it the left-hand variant of that Either. Read more
source§

fn right_sink<Si1>(self) -> Either<Si1, Self>
where Si1: Sink<Item, Error = Self::Error>, Self: Sized,

Wrap this stream in an Either stream, making it the right-hand variant of that Either. Read more
source§

fn poll_ready_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_ready on Unpin sink types.
source§

fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error>
where Self: Unpin,

A convenience method for calling Sink::start_send on Unpin sink types.
source§

fn poll_flush_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_flush on Unpin sink types.
source§

fn poll_close_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_close on Unpin sink types.
source§

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

source§

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>,

source§

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>,

source§

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