postgresql - 从异步主要调用的 Rust Postgres(同步)驱动程序导致“无法从运行时内启动运行时”
问题描述
我有一个项目需要使用 postgres 同步驱动程序(第三方库需要同步回调),它公开了一个 GRPC API。
不幸的是,rust-postgres 做了一个block_on
嵌套的#[tokio::main]
最小的复制将是:
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
因为这意味着将所有内容重新包装为同步。
解决方案
您可以将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 代码之间获取数据。
将尽可能多的客户端和错误处理填充到新线程中,以限制跨线程的对话,以防出现性能瓶颈。
推荐阅读
- django - 尽管使用了模板,但 AsserrtTemplateUsed 失败...?
- angular - 电子 IPC 消息
- go - Golang gRPC 客户端连接到 GKE
- python - 将日期对象从 python 插入到 mysql
- javascript - Show custom text in number input
- c# - Xamarin 表单分组列表视图不显示迭代行
- reactjs - React-Konva 带钩子的免费绘图
- java - 下次我运行代码时如何更新我的数组
- javascript - 将 css 注入跨域本地 iframe
- c++ - 我的迭代器实现不起作用,它有什么问题?