美文网首页Rust 学习笔记
rust - 异步学习 async,await,future

rust - 异步学习 async,await,future

作者: 国服最坑开发 | 来源:发表于2020-02-27 16:29 被阅读0次

    0x01 最简单的异步 async

    The most common way to run a Future is to .await it. When .await is called on a Future, it will attempt to run it to completion.
    执行 Future的最简单方法就是调用 await

    use futures::executor::block_on;
    
    async fn say_hi() {
        println!("nice");
    }
    
    fn main() {
        let future = say_hi();
        // block the current thread until provided future
        block_on(future);
    }
    

    使用async 来修饰一个方法, 表示此方法是一个异步任务, 然后在主线程里使用一个执行器宏 block_on 来等待运行结果

    0x02 关键字 await

    
    async fn lear_song() {
        println!("learn song");
    }
    
    async fn sing_song() {
        println!("sing song");
    }
    
    async fn dance() {
        println!("learn dance");
    }
    
    async fn learn_and_sing() {
        // study song, and wait
        let song = lear_song().await;
        // then sing song
        sing_song().await;
    }
    
    async fn async_main(){
        let f1 = learn_and_sing();
        let f2 = dance();
        futures::join!(f1,f2);
    }
    
    fn main() {
        block_on(async_main());
        println!("done");
    }
    
    1. 在一个async方法中, 可以执行其他异步任务. 但如果需要顺序执行这些异步任务时, 就需要在上一个任务的后面,执行await方法.
    2. 如果想实现barrier类似的效果, 可以通过 futures::join 方法来实现.
    0x2.1 展示一下在actix-web的方法中, 返回一个http请求的示例
    [dependencies]
    actix-web = "2.0"
    actix-rt = "1.0"
    
    reqwest = { version = "0.10", features = ["json"] }
    tokio = { version = "0.2", features = ["full"] }
    
    
    use actix_web::{Responder, HttpResponse, HttpServer, web, App};
    
    async fn index() -> impl Responder {
        let resp = reqwest::get("https://httpbin.org/ip").await;
        if let Ok(rsp) = resp {
            let body = rsp.text().await.unwrap();
            HttpResponse::Ok().body(body)
        }
        else {
            HttpResponse::Ok().body("no content!")
        }
    }
    
    #[actix_rt::main]
    async fn main() -> std::io::Result<()> {
        HttpServer::new(|| {
            App::new()
                .route("/", web::get().to(index))
        })
            .bind("127.0.0.1:8088")?
            .run()
            .await
    }
    

    相关文章

      网友评论

        本文标题:rust - 异步学习 async,await,future

        本文链接:https://www.haomeiwen.com/subject/rdwthhtx.html