Rust Lazy初始化异步字符串?

问题描述

我想在线程之间全局异步之间缓存JWKS。 所以我这样做了:

use std::lazy::{Lazy,OnceCell};

static JWKS: Lazy<String> = Lazy::new(|| {
    let authority = std::env::var("AUTHORITY").expect("Finding AUTHORITY env var.");
    let uri = format!("{}{}",authority,".well-kNown/jwks.json");
    let res = reqwest::blocking::get(&uri).expect("To get the JWKS");
    res.text().expect("JWKS to contain something.")
});

但是我得到了这个错误

error[E0277]: `std::cell::Cell<std::option::Option<fn() -> std::string::String>>` cannot be shared between threads safely
  --> src/auth.rs:35:1
   |
35 | / static JWKS: Lazy<String> = Lazy::new(|| {
36 | |     let authority = std::env::var("AUTHORITY").expect("Finding AUTHORITY env var.");
37 | |     let uri = format!("{}{}",".well-kNown/jwks.json");
38 | |     let res = reqwest::blocking::get(&uri).expect("To get the JWKS");
39 | |     res.text().expect("JWKS to contain something.")
40 | | });
   | |___^ `std::cell::Cell<std::option::Option<fn() -> std::string::String>>` cannot be shared between threads safely
   |
   = help: within `std::lazy::Lazy<std::string::String>`,the trait `std::marker::Sync` is not implemented for `std::cell::Cell<std::option::Option<fn() -> std::string::String>>`
   = note: required because it appears within the type `std::lazy::Lazy<std::string::String>`
   = note: shared static variables must have a type that implements `Sync`

是否可以在铁锈中进行这种缓存?

我知道我可以使用某种全局配置结构初始化所有内容。但是随后需要在actix中将其传递下来。

编辑:

我找到了SyncLazy,所以我将代码更改为:

static JWKS: SyncLazy<String> = SyncLazy::new(|| {
    let authority = std::env::var("AUTHORITY").expect("Finding AUTHORITY env var.");
    let uri = format!("{}{}",".well-kNown/jwks.json");
    let res = reqwest::blocking::get(&uri).expect("To get the JWKS");
    res.text().expect("JWKS to contain something.")
});

现在的问题是运行代码时出现此错误

thread 'actix-rt:worker:0' panicked at 'Cannot drop a runtime in a context where blocking is not allowed. This happens when a runtime is dropped from within an asynchronous context.',/home/jonasi/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.22/src/runtime/blocking/shutdown.rs:49:21
stack backtrace:

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...