Module 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("field `redis` should be a table");
    let database = config
        .get_str("database")
        .expect("field `database` 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
Data wrapper.
SharedData
Shared data wrapper.
State
A state is a record of the env, config and associated data.

Enums§

Env
Application running environment.