Module zino_core::state

source ·
Expand description

Application scoped state.

§Examples

# config/config.dev.toml

[redis]
host = "127.0.0.1"
port = 6379
database = "dbnum"
username = "some_user"
password = "hsfU4Y3aRbxVNuLpVG5T+wb9jIDdQyaUIiPgeQrP0ZRM1g"

//! src/extension/redis.rs

use parking_lot::Mutex;
use redis::{Client, Connection, RedisResult};
use zino_core::{state::State, LazyLock};

#[derive(Debug, Clone, Copy)]
pub struct Redis;

impl Redis {
    #[inline]
    pub fn get_value(key: &str) -> RedisResult<String> {
        REDIS_CONNECTION.lock().get(key)
    }

    #[inline]
    pub fn set_value(key: &str, value: &str, seconds: u64) -> RedisResult<()> {
        REDIS_CONNECTION.lock().set_ex(key, value, seconds)
    }
}

static REDIS_CLIENT: LazyLock<Client> = LazyLock::new(|| {
    let config = State::shared()
        .get_config("redis")
        .expect("the `redis` field should be a table");
    let database = config
        .get_str("database")
        .expect("the `database` field should be a str");
    let authority = State::format_authority(config, Some(6379));
    let url = format!("redis://{authority}/{database}");
    Client::open(url)
        .expect("fail to create a connector to the redis server")
});

static REDIS_CONNECTION: LazyLock<Mutex<Connection>> = LazyLock::new(|| {
    let connection = REDIS_CLIENT.get_connection()
        .expect("fail to establish a connection to the redis server");
    Mutex::new(connection)
});

Structs§

  • Data wrapper.
  • Shared data wrapper.
  • A state is a record of the env, config and associated data.

Enums§

  • Application running environment.