Asynchronous 如何在Warp内部生成一个线程来处理异步行为?

Asynchronous 如何在Warp内部生成一个线程来处理异步行为?,asynchronous,rust,rust-warp,Asynchronous,Rust,Rust Warp,我将Warp板条箱用于web服务,但在从非异步主服务器运行它时遇到问题 我尝试过几种方法,最接近的方法是: 货舱 [dependencies] warp = "0.3" futures = "0.3" 代码: 使用std::collections::HashMap; 使用std::thread::{sleep,spawn}; 使用std::时间; 使用warp::{Filter}; 使用futures::executor::block_on; 异步fn

我将Warp板条箱用于web服务,但在从非异步主服务器运行它时遇到问题

我尝试过几种方法,最接近的方法是:

货舱

[dependencies]
warp = "0.3"
futures = "0.3"
代码:

使用std::collections::HashMap;
使用std::thread::{sleep,spawn};
使用std::时间;
使用warp::{Filter};
使用futures::executor::block_on;
异步fn get\u ap\u list()->结果{
让mut result=HashMap::new();
//TODO:获取完整的列表
结果。插入(“SSID”、“rossless_24”);
确定(warp::reply::json(&result))
}
异步fn启动\u ap\u服务器(){
println!(“AP服务器”);
让get_ap=warp::get()
和(扭曲::路径(“ap”))
和(扭曲::路径(“列表”))
.和(warp::path::end())
。然后(获取ap列表);
翘曲:发球(得到球)
.运行(([0,0,0,0],3030))
等候
}
//这个中间函数似乎有点多余,但我似乎无法直接生成异步服务器
fn初始化ap_服务器(){
println!(“初始AP服务器”);
让future=start_ap_server();
封锁(未来);
}
fn main(){
让_t1=繁殖(移动| |{
初始化ap_服务器()
});
//确保main仍在运行
环路{
println!(“测试用活着”);
睡眠(时间:持续时间:从_millis(5000));
}
}
这似乎有效,但我得到:

线程“”在“没有反应堆运行,必须从Tokio 1.x运行时的上下文调用”时陷入恐慌,/home/tross/.cargo/registry/src/github.com-1ec6299db9ec823/Tokio-1.5.0/src/runtime/context.rs:18:26
通过谷歌搜索,我发现这可能是Tokio版本不匹配,但我的依赖项中甚至没有Tokio,我是从Warp获得的


退一步,有没有更简单的方法来得到我想要的?我只想启动一些异步代码运行(可能在它自己的线程上),同时让main保持活跃和愉快。

warp
本身确实引入了
tokio
依赖项,但它没有
rt
功能:

// warp/Cargo.toml
...
tokio = { version = "1.0", features = ["fs", "sync", "time"] }
...
因此,没有运行时来执行未来。为了获得
tokio::Runtime
,您可以显式生成
运行时
,并在该运行时上调用
block\u

// This intermediate function seem a bit redundant but I can't seem to spawn the async server directly
fn init_ap_server() {
    println!("Init AP server");
    let runtime = Builder::new_current_thread()
        .enable_io()
        .build()
        .expect("Failed to create runtime");

    let future = start_ap_server();
    runtime.block_on(future);
}
与:


您必须将tokio添加为显式依赖项,并创建一个运行时供warp使用,warp需要安排一个活动的tokio运行时,即使您不想异步ify
main
(哪…为什么?)。如果您绝对不想使用
tokio::main
(这又是为什么呢?),您可以查看tokio文档,或者只是转储一个宏扩展的warp hello world来查看如何初始化tokio运行时。这不是tokio版本不匹配。这是Warp期望的Tokio executor与
futures::block_on
提供的executor之间的不匹配。没有运行时来执行futures on-这不可能是正确的。如果存在正在运行的异步代码,则存在一个运行时。在OPs示例中,由于没有可用的运行时,所以没有执行异步代码,因此出现了恐慌?某些异步代码正在执行,这导致了恐慌。(并且是正确的)-问题是,您无法在未来的执行器上执行这些特定的未来。只有当某个异步执行器将代码驱动到如此地步时,才会执行这种恐慌。期货箱有很多特点
futures::executor::block_on
是一个执行器/运行时,但它没有能力运行那些特定的Tokio futures。感谢您的回答和所有发表评论的人!你是对的,我错过了运行时。随着这一变化,它似乎如预期的那样起作用。
[dependencies]
warp = "0.3"
tokio = {version = "1", features = ["rt"] }