我有一个项目,其中我需要使用postgres同步驱动程序(第三方库需要同步回调),并且它公开了一个GRPC API。
不幸的是,rust-postgres做了一个与#[tokio::main]嵌套的block_on
最小repro值为:
use postgres::{Client, NoTls};
#[tokio::main]
async fn main() {
let _client = Client::connect("host=localhost dbname=template1 user=postgres", NoTls).unwrap();
}使用依赖关系:
tokio = { version = "1.6.1", features = ["rt-multi-thread", "macros"] }
postgres = "0.19.1"我得到了错误:
'Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.'SQL查询的性能并不重要,我可以很好地阻止它们。我不想切换到tokio-postgres,因为这意味着重新包装所有东西都是同步的。
发布于 2021-08-06 03:55:49
您可以将rust-postgres代码派生到它自己的独立线程中。
use postgres::{Client, NoTls};
#[tokio::main]
async fn main() {
std::thread::spawn(|| {
let _client = Client::connect("host=localhost dbname=template1 user=postgres", NoTls).unwrap();
});
}然后通过标准方法设置线程间通信,例如tokio::sync::mpsc消息传递,以在数据库驱动程序和Rust代码的其余部分之间获取数据。
在新线程中尽可能多地填充客户端和错误处理,以限制线程之间的通信,以防出现性能瓶颈。
https://stackoverflow.com/questions/67851017
复制相似问题