Back

rust - actix 1 安装与hello world

发布时间: 2020-05-16 10:48:00

参考:https://actix.rs/docs/getting-started/

actix 是一个actor 架构的框架(大概可以这样说), 可以认为是目前web项目的极速。 (几乎最快的语言+最快的架构)

之前我曾经尝试过 erlang 家族的 elixir, 使用pheonix框架。  (听说 畅思就是这样做的)

不过后来项目太赶, 没有持续下去。 

现在出来了rust, 而且rust 社区明显更加火爆一些,口碑也非常好,所以可以认为这是上车的最好时间了。

安装:

需要  rust > 1.39 

$ rustup update 

$ cargo new test_rust  并cd 该目录

$ vim Cargo.toml

[dependencies] 下面添加:

actix-web = "2.0"
actix-rt = "1.0"

然后修改src/main.rs 文件,添加如下内容:

// 引入对应的包
use actix_web::{web, App, HttpResponse, HttpServer, Responder};

// 定义了一个action (来处理某个route ) 

async fn index1() -> impl Responder {
    HttpResponse::Ok().body("hello, 1")
}

async fn index2() -> impl Responder {
    HttpResponse::Ok().body("hello, 2")
}

// 这里使用 类似于java语言中的doclet ,来实现 “非代码” 层面的代码功能。
#[actix_rt::main]
async fn main() -> std::io::Result<()> {           	// 定义了返回值,不用变
    HttpServer::new( || {			   	// 定义了http server
        App::new()					// 定义了App 
            .route("/hi1", web::get().to(index1))	// 定义了一个路由
            .route("/hi2", web::get().to(index2))
    })  
    .bind("127.0.0.1:8088")?				// 定义了运行的地址
    .run()
    .await
}

Ok, Err 都是std::io::Result的内容,可以认为是标准语法 ,表示操作成功或者失败。用的极其广泛

然后运行:

$ cargo run 

   Compiling test_actix v0.1.0 (/workspace/test_rust/test_actix)
    Finished dev [unoptimized + debuginfo] target(s) in 9.22s
     Running `target/debug/test_actix`

可以看到 服务器已经跑起来了。 访问:http://localhost:8088/hi1  就可以看到内容了。 

benchmark: 使用 ab 来测量,在我的笔记本上是 4200 ~ 4800 每秒。  ( 同时并发1000请求) 。据说在服务器上可以跑到7000? 

Back