Rust安装使用

Window 安装

这里主要针对 Window 平台, 对于 Linux 平台其实只需要安装官方 Rustup 设置即可

主要原因是不想安装 VisualStudio 太多依赖

1
2
3
4
5
6
7
# 主要最小化安装需要 CPP 编译器即可, 具体地址如下
https://visualstudio.microsoft.com/visual-cpp-build-tools/
# 点击 exe 之后需要选择最小化的 CPP 编译工具
# 1. 选择 `单个组件`
# 2. 只勾选以下组件
# - MSVC v{最新版本} - VS{最新版本} C++ x64/x86 生成工具(我目前用的是 v143, v14.44-17.14版本)
# - Windows 10/11 SDK(对应你电脑系统版本, 目前用的 Win11 10.0.2.28000)

完成之后就是安装 window 的依赖, 这里建议命令行全局安装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 这里我习惯放置于 C:\rust 之中, 建议先创建好目录并且在管理员模式下窗口执行
# 分配的目录如下:
# - 工具链: C:\rust\rustup
# - 包管理: C:\rust\cargo
# 最好需要分配好全局环境变量
# - RUSTUP_HOME: C:\rust\rustup
# - CARGO_HOME: C:\rust\cargo
# - Path: 内部追加 %CARGO_HOME%\bin 目录的变脸
# 完成之后重新打开启动 rustup-init.exe, 保持默认即可
# 最后重新打开终端输入以下命令确认安装成功
rustc -V
cargo -V

# 确认工具链版本
rustup show

一般我更喜欢全局安装共享下载的工具链, 避免放置于用户个人文档之中产生垃圾文件

Web 搭建

这里目前 Rust 社区提供的方案有以下方案

  • Actix-Web

  • Rocket

  • Axum

目前比较推荐采用 Axum 作为首选的方案, 是 Tokio(官方异步标准) 推出的标准 Web 开发库, 这里采用命令先创建项目和依赖

1
2
3
4
5
6
7
8
9
10
# 创建名为 nova_web 的项目
cargo new nova_web
cd nova_web

# 引入最新的 axum 组件
cargo add axum tokio serde serde_json

# 开启对应feature
cargo add tokio --features rt-multi-thread,macros
cargo add serde --features derive

最后就是编写对应服务文件代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use axum::extract::Query;
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router as APIRouter};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::time::SystemTime;
use tokio::net::TcpListener;

/// 响应参数
#[derive(Serialize)]
struct EchoResponse {
name: String,
time: u64,
}

/// 请求参数
#[derive(Debug, Deserialize)]
struct EchoRequest {
pub name: Option<String>,
}

#[tokio::main]
async fn main() {
// 创建路由
let app = APIRouter::new()
.route(
"/",
get(|Query(params): Query<EchoRequest>| async move {
// 判断时候带有 ?name=test 参数
let name = match &params.name {
Some(name) if !name.trim().is_empty() => name.to_string(),
_ => "MeteorCat".to_string(),
};

// 响应数据
Json(EchoResponse {
name,
time: SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs(),
})
}),
)
.route("/fail", get(|| async {
panic!("手动抛出业务异常");
Json(EchoResponse {
name: "test".to_string(),
time: SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs(),
})
}))
.fallback(|| async {
(StatusCode::NOT_FOUND, Json(json!({})))
});

// 启动服务
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}