English 中文(简体)
在ru柴油交易中可以发挥yn的作用。
原标题:is it possible to run a async function in rust diesel transaction

I am using rust diesel transaction to do some async task, now I am tried to use a new tokio runtime like this(this just a minimal demo to show the issue):

use diesel::result::Error;
use diesel::Connection;
use rust_wheel::config::db::config;
use tokio::runtime::Runtime;

#[tokio::main]
async fn main() {
    let mut connection = config::connection("TEX_DATABASE_URL".to_string());
    let _trans_result: Result<(), Error> = connection.transaction(|_connection| {
        let rt = Runtime::new().unwrap();
        Ok(rt.block_on(async { do_create_proj_trans().await }))
    });
}

async fn do_create_proj_trans() {
    println!("doing...")
}

该法典显示错误,如:

thread  main  panicked at  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. , /Users/xiaoqiangjiang/.cargo/registry/src/mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd/tokio-1.32.0/src/runtime/scheduler/multi_thread/mod.rs:86:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

当我去掉起算时间时,就显示出这样的错误:

`await` is only allowed inside `async` functions and blocks
only allowed inside `async` functions and blocks

能否在ru式柴油机体内发挥合成功能? 货物:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
tokio = { version = "1.17.0", features = ["full"] }
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
futures = "0.3"
tokio-stream = "0.1"
rust_wheel = { git = "https://github.com/jiangxiaoqiang/rust_wheel.git", branch = "diesel2.0" }
log4rs = "1.2.0"
log = "0.4.0"
diesel = { version = "2.1.0", features = ["postgres","64-column-tables","chrono","serde_json"] }
最佳回答
问题回答

是的,这是可能的,但你在用于推动任务的read子里重新尝试这样做,并且你可以这样做。 相反,在一项任务中,它把 锁在task:spawn_blocking:

#[tokio::main]
async fn main() {
    let _trans_result: Result<(), Error> = tokio::task::spawn_blocking(|| {
        let mut connection = config::connection("TEX_DATABASE_URL".to_string());
        connection.transaction(|_connection| {
            let rt = tokio::runtime::Handle::current();
            Ok(rt.block_on(async { do_create_proj_trans().await }))
        })
    }).await.unwrap();
}

我也选择使用目前的运行时间,而不是制造不同的时间。

在“@cafce25”的答复基础上,我做了一个可调用的内容,帮助解决:

pub fn await_helper<F: Future + Send>(future: F) -> F::Output
where
    <F as Future>::Output: Send +  static,
{
    task::block_in_place(move || Handle::current().block_on(future))
}

可在以下地点使用<代码>await_helper功能:.await。 或您可将您的整个交易逻辑列入<条码>星号>{},然后将<条码>-- 助。 如果您愿意,然后在您的交易逻辑中完全使用<代码>.await。

这在<代码>task:block_in_place的文件中作为实例。 职能:

https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html#examples

注:较早 我试验使用了<代码>std:thread:spawn <>/code>,然后用<代码>阻断今后 sp的透镜。 Handle:block_on。 这是一个微妙的问题——如果你想要加入这一版,await_helper。 之后,请上<代码>的电话:读:JoinHandle:join 封锁了 calling子,它属于迫害者,是坏的,可以造成僵局。 你们必须使用<条码>tokio:task:block_in_place,而不是在概念上阻碍这项任务,而不是“OS”透镜。

相比之下,见柴油问题建议的另一种作为合成支持的办法:

See also this tokio issue discussion: https://github.com/tokio-rs/tokio/discussions/4563 See also this blog post: https://ryhl.io/blog/async-what-is-blocking/

I chose to do this instead of using diesel-async because migrating a large project from diesel to diesel-async is not trivial, and it also implies significant changes to the underlying implementation -- moving from libpq, the C library that the vast majority of projects across all languages ultimately use to talk to a postgres server, to a pure-rust rewrite called tokio-postgres.

或许可以使用这一条,但我想首先使用<条码>req 西在柴油交易中提出“吉卜赛人”申请。 放弃<代码>libpq,以达到这一目的似乎是一种根本性的变化,也许不是我为之讨价还价。





相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...

热门标签