微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Rust Lazy初始化异步字符串?

如何解决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.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?