Config

Struct Config 

Source
pub struct Config {
    pub path: String,
    pub host: String,
    pub port: u16,
    pub access_key: String,
    pub access_secret: String,
    pub retry_times: u8,
    pub retry_interval: u64,
}
Expand description

§Configuration.

§Fields

  • path: Path to the unix socket or tcp address.
  • host: Host of the tcp address.
  • port: Port of the tcp address.
  • access_key: Access key for authentication.
  • access_secret: Access secret for authentication.
  • retry_times: Retry times when connection failed.
  • retry_interval: Retry interval when connection failed.

§Default values

  • path: Empty string.
  • host: “0.0.0.0”.
  • port: 60001.
  • access_key: Empty string.
  • access_secret: Empty string.
  • retry_times: 3.
  • retry_interval: 60.

§Environment variables (when config file not exists, cover default values)

  • AMQ_PATH: Path to the unix socket or tcp address.
  • AMQ_HOST: Host of the tcp address.
  • AMQ_PORT: Port of the tcp address.
  • AMQ_ACCESS_KEY: Access key for authentication.
  • AMQ_ACCESS_SECRET: Access secret for authentication.
  • AMQ_RETRY_TIMES: Retry times when connection failed.
  • AMQ_RETRY_INTERVAL: Retry interval when connection failed.

§Example

path = "/tmp/amq.sock"  # use host and port if path is empty
host = "127.0.0.1"      # ignored if path is not empty
port = 60001            # ignored if path is not empty
access_key = "access_key"
access_secret = "access_secret"
retry_times = 3
retry_interval = 60
export AMQ_PATH="/tmp/amq.sock"
export AMQ_HOST="127.0.0.1"
export AMQ_PORT=60001
export AMQ_ACCESS_KEY="access_key"
export AMQ_ACCESS_SECRET="access_secret"
export AMQ_RETRY_TIMES=3
export AMQ_RETRY_INTERVAL=60

Fields§

§path: String§host: String§port: u16§access_key: String§access_secret: String§retry_times: u8§retry_interval: u64

Implementations§

Source§

impl Config

Source

pub fn new() -> Result<Self, Box<dyn Error>>

§Create a new configuration.
  1. use the first argument as config file path, if exists.
  2. use the ./config.toml as config file path.
  3. use environment variables to cover default values.
  4. use default values.
Examples found in repository?
examples/sync_pubsub.rs (line 15)
11async fn main() -> Result<(), Box<dyn Error>> {
12    let state = Arc::new(Mutex::new(0));
13
14    loop {
15        let config = Config::new().unwrap();
16
17        let mut client = SyncClient::new(config, state.clone());
18
19        let rx = match client.connect() {
20            Ok(rx) => rx,
21            Err(e) => {
22                println!("Connection error: {}", e);
23                sleep(Duration::from_secs(1));
24                continue;
25            }
26        };
27
28        client.subscribe("topic", |state, msg| {
29            let mut state = state.lock().unwrap();
30            *state += 1;
31            println!("Received message: {} {:?}", state, msg);
32        })?;
33
34        let should_exit;
35        loop {
36            let result = rx.try_recv();
37            match result {
38                Ok(AmqError::TcpServerClosed) => {
39                    should_exit = true;
40                    break;
41                }
42                Ok(e) => {
43                    println!("{}", e);
44                    should_exit = false;
45                    break;
46                }
47                Err(TryRecvError::Empty) => {
48                    sleep(Duration::from_secs(1));
49                    let _ = client.publish("topic", "Hello, world!".as_bytes().to_vec());
50                }
51                Err(e) => {
52                    println!("Receive signal error: {:?}", e);
53                    should_exit = false;
54                    break;
55                }
56            }
57        }
58
59        if should_exit {
60            break;
61        }
62
63        println!("Reconnecting...");
64    }
65
66    Ok(())
67}
More examples
Hide additional examples
examples/async_pubsub.rs (line 11)
7async fn main() -> Result<(), Box<dyn Error>> {
8    let state = Arc::new(Mutex::new(0));
9
10    loop {
11        let config = Config::new().unwrap();
12
13        let mut client = AsyncClient::new(config, state.clone());
14
15        let rx = match client.connect().await {
16            Ok(rx) => rx,
17            Err(e) => {
18                println!("Connection error: {}", e);
19                sleep(Duration::from_secs(1)).await;
20                continue;
21            }
22        };
23
24        client
25            .subscribe("topic", |state, msg| async move {
26                let mut state = state.lock().await;
27                *state += 1;
28                println!("Received message: {} {:?}", state, msg);
29            })
30            .await?;
31
32        let should_exit = select! {
33            // Receive signal when connection closed
34            result = rx => {
35                client.shutdown().await;
36
37                match result {
38                    // Server closed connection
39                    Ok(AmqError::TcpServerClosed) => {
40                        true
41                    }
42                    // Other error
43                    Ok(e) => {
44                        println!("{}", e);
45                        false
46                    }
47                    Err(e) => {
48                        println!("Receive signal error: {:?}", e);
49                        false
50                    }
51                }
52            }
53
54            // Send message every 1s
55            _ = async {
56                loop {
57                    sleep(Duration::from_secs(1)).await;
58                    let _ = client.publish("topic", "Hello, world!".as_bytes().to_vec()).await;
59                }
60            } => {
61                false // Exit loop on error, and reconnect
62            }
63        };
64
65        if should_exit {
66            break;
67        }
68
69        println!("Reconnecting...");
70    }
71
72    Ok(())
73}
Source

pub fn get_address(&self) -> String

Source

pub fn get_unix_path(&self) -> String

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a duplicate 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 Default for Config

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Config

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Config

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnwindSafe for Config

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,