Skip to content

How do I access state that is Send + !Sync in Axum? #2306

Answered by Zk2u
Zk2u asked this question in Q&A
Discussion options

You must be logged in to vote

I've used thread local storage for it to work as expected without having to go through Axum's state. Thank you for an awesome library!

/// CELL is shared between ALL threads
static CELL: OnceLock<Mutex<sled::Db>> = OnceLock::new();

thread_local! {
    /// Thread local DB clone
    static DB: Rc<sled::Db> = Rc::new(CELL.get_or_init(|| {
        debug!("DB open on thread {}", std::thread::current().name().unwrap_or("unknown"));
        Mutex::new({
            let mut config = sled::Config::default();
            config.flush_every_ms = None;
            sled::Db::open_with_config(&config).unwrap()
        })
    }).lock().unwrap().clone());
}

pub fn thread_local_db() -> Rc<sled::Db> {
    

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Zk2u
Comment options

Answer selected by Zk2u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants