Documentation

xboot

With the help of linkme, an asynchronous function can be called to initialize static variables.

This allows connecting to the database before the program starts and setting it as a module-level variable. For reference, see xkv: redis global connector.

借助 linkme,调用异步函数初始化静态变量。

可在程序启动之前连上数据库,并设置为一个模块级别的变量,参考 xkv: redis 全局连接器

use aok::{Result, OK};
pub use async_wrap::Wrap;
use tracing::info;

pub mod inner {
  use aok::{Result, OK};
  use async_lazy::Lazy;
  use tokio::time::{sleep, Duration};
  use tracing::info;

  pub struct Client {}

  impl Client {
    pub async fn test(&self) {
      info!("client test success");
    }

    pub async fn connect(&self) -> Result<()> {
      info!("Sleeping for 3 seconds...");
      sleep(Duration::from_secs(3)).await;
      OK
    }
  }

  pub static CLIENT: Lazy<Client> = Lazy::const_new(|| {
    Box::pin(async {
      let client = Client {};
      loop {
        match client.connect().await {
          Ok(_) => {
            return client;
          }
          Err(err) => {
            tracing::error!("connect error: {}", err);
          }
        }
      }
    })
  });

  pub fn async_init() -> xboot::Task {
    tokio::task::spawn(async {
      use std::future::IntoFuture;
      CLIENT.into_future().await;
      OK
    })
  }

  #[linkme::distributed_slice(xboot::ASYNC)]
  static INIT: xboot::AsyncFn = async_init;
}

pub static CLIENT: Wrap<inner::Client> = Wrap::<inner::Client>(&inner::CLIENT);

#[tokio::main]
async fn main() -> Result<()> {
  xboot::init().await?;
  info!("inited");
  CLIENT.test().await;
  OK
}

About

This project is an open-source component of i18n.site ⋅ Internationalization Solution.

关于

本项目为 i18n.site ⋅ 国际化解决方案 的开源组件。