Function async_nats::connect

source ·
pub async fn connect<A: ToServerAddrs>(addrs: A) -> Result<Client, ConnectError>
Expand description

Connects to NATS with default config.

Returns cloneable Client.

To have customized NATS connection, check ConnectOptions.

§Examples

§Single URL

let mut nc = async_nats::connect("demo.nats.io").await?;
nc.publish("test", "data".into()).await?;

§Connect with Vec of ServerAddr.

#[tokio::main]
use async_nats::ServerAddr;
let client = async_nats::connect(vec![
    "demo.nats.io".parse::<ServerAddr>()?,
    "other.nats.io".parse::<ServerAddr>()?,
])
.await
.unwrap();

§with Vec, but parse URLs inside crate::connect()

#[tokio::main]
use async_nats::ServerAddr;
let servers = vec!["demo.nats.io", "other.nats.io"];
let client = async_nats::connect(
    servers
        .iter()
        .map(|url| url.parse())
        .collect::<Result<Vec<ServerAddr>, _>>()?,
)
.await?;

§with slice.

#[tokio::main]
use async_nats::ServerAddr;
let client = async_nats::connect(
   [
       "demo.nats.io".parse::<ServerAddr>()?,
       "other.nats.io".parse::<ServerAddr>()?,
   ]
   .as_slice(),
)
.await?;