Rust Web 開發實戰 -後端--2 Web Server 和數據庫
上一篇文章《Rust 全棧開發實戰 (Rust on Nails)-1 配置開發環境》,我們配置好了開發環境,在這一篇中,我們開始設置 Web Server 和數據庫。
Web Server
我們研究了 Actix Web、Tokio Axum 和 Rocket。選擇 Axum 是因爲它的維護非常活躍,並且增量構建時間最快。
大多數 Rust 的 Web Server 項目都以類似的方式運行,也就是你配置一個路由和一個響應該路由的函數。
響應路由的函數可以有參數。這些參數可能是結構體、數據庫池或表單數據,由框架傳遞給函數。
在 app/Cargo.toml 中添加以下內容:
[dependencies]
axum = "0"
tokio = { version = "1", default-features = false, features = ["macros", "rt-multi-thread"] }
然後更新 app/src/main.rs:
use axum::{response::Html, routing::get, Router};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// build our application with a route
let app = Router::new().route("/", get(handler));
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
運行 cargo run,然後打開瀏覽器,輸入 http://localhost:3000 顯示:
數據庫
該架構不會限制你使用 MySQL (MariaDB?) 或其他關係數據庫。
當我們安裝我們的開發容器時,我們已經安裝了 Postgres,但是我們沒有安裝 Postgres 命令行客戶端。所以在. devcontainer/Dockerfile 中加入以下內容:
# Install psql 14
RUN sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' \
&& wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - \
&& apt-get -y update \
&& apt-get -y install postgresql-client \
&& apt-get autoremove -y && apt-get clean -y
在. devcontainer/.env 中加入以下內容:
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable
重新啓動你的開發容器,你現在應該可以訪問 Postgres。即:
psql $DATABASE_URL
psql (14.2 (Debian 14.2-1.pgdg110+1), server 14.1 (Debian 14.1-1.pgdg110+1))
Type "help" for help.
postgres=# \dt
Did not find any relations.
postgres=# \q
我們將反覆使用種方法,當我們在解決方案中添加工具時,我們會將其添加到開發容器中,這確保了我們總是可以重現我們的開發環境。
下一篇文章,我們將給應用加配置及設置數據庫工具。
本文翻譯自:
https://cloak.software/blog/rust-on-nails/#development-environment-as-code
coding 到燈火闌珊 專注於技術分享,包括 Rust、Golang、分佈式架構、雲原生等。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/fP8xsBlzMWWus1IVKf5mQw