Rust Web开发实战(后端)-2 Web Server和数据库

2022年7月7日 200点热度 0人点赞 0条评论



上一篇文章《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 14RUN 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_URLpsql (14.2 (Debian 14.2-1.pgdg110+1), server 14.1 (Debian 14.1-1.pgdg110+1))Type "help" for help.
postgres=# \dtDid not find any relations.postgres=# \q

我们将反复使用种方法,当我们在解决方案中添加工具时,我们会将其添加到开发容器中,这确保了我们总是可以重现我们的开发环境。

下一篇文章,我们将给应用加配置及设置数据库工具。

本文翻译自:

https://cloak.software/blog/rust-on-nails/#development-environment-as-code


13330Rust Web开发实战(后端)-2 Web Server和数据库

root

这个人很懒,什么都没留下

文章评论