温馨提示×

Rust在CentOS上的Web开发如何入门

小樊
45
2025-12-19 10:39:45
栏目: 编程语言

在 CentOS 上入门 Rust Web 开发

一 环境准备

  • 安装基础编译工具与包管理源,更新系统并安装常用开发工具:
    • sudo yum update -y
    • sudo yum groupinstall -y “Development Tools”
    • sudo yum install -y epel-release curl
  • 安装 Rust 工具链(rustup),并将 cargo 加入 PATH:
    • curl --proto ‘=https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh
    • 在 ~/.bashrc 或 ~/.zshrc 中添加:export PATH=“$HOME/.cargo/bin:$PATH”,然后执行 source ~/.bashrc
    • 验证:rustc --version 与 cargo --version 应返回版本号
  • 可选:配置国内镜像加速依赖下载(~/.cargo/config.toml)
    • [source.crates-io] replace-with = ‘ustc’
    • [source.ustc] registry = “https://mirrors.ustc.edu.cn/crates.io-index”"

二 选择框架与创建项目

  • 常见框架与定位
    • Actix-web:基于 Actor 模型,生态成熟,适合高并发与 RESTful API
    • Hyper:底层 HTTP 库,灵活可定制,适合学习 HTTP 或自研框架
    • Pingora:基于 Rust 的高性能框架,适合反向代理、网关等场景
  • 使用 Cargo 创建项目并运行
    • cargo new rust-web-demo && cd rust-web-demo
    • cargo run 验证项目可构建运行

三 编写第一个 Web 服务 Actix-web

  • 添加依赖(Cargo.toml)
    • [dependencies]
      • actix-web = “4”
  • 示例代码(src/main.rs)
    • use actix_web::{get, App, HttpServer, Responder};
      • #[get(“/”)] async fn index() -> impl Responder { “Hello, Rust on CentOS!” }
      • #[actix_web::main] async fn main() -> std::io::Result<()> {
        • HttpServer::new(|| App::new().service(index))
          • .bind(“127.0.0.1:8080”)?
          • .run()
          • .await
        • }
  • 运行与验证
    • cargo run
    • 在浏览器访问:http://127.0.0.1:8080

四 连接数据库 Diesel ORM

  • 添加依赖(Cargo.toml)
    • [dependencies]
      • diesel = { version = “1.4”, features = [“sqlite”] }
      • dotenv = “0.15”
  • 初始化与配置
    • 在项目根目录创建 .env:DATABASE_URL=sqlite://./test.db
    • 生成迁移:diesel setup
    • 创建迁移文件:diesel migration generate create_users
    • 编辑迁移(up.sql / down.sql),例如创建 users 表
    • 执行迁移:diesel migration run
  • 简单示例(演示连接与插入)
    • 在代码中建立连接、插入数据、查询数据(遵循 Diesel 的查询 DSL)
  • 说明
    • Diesel 提供类型安全的查询与迁移工具,适合中小型项目快速落地

五 部署与上线

  • 构建发布版本
    • cargo build --release(产物在 target/release/)
  • 以最小示例服务运行(生产环境建议使用 systemd 或类似守护进程管理)
    • nohup ./target/release/your_app &
  • 使用 Nginx 反向代理与 HTTPS
    • 安装 Nginx:sudo yum install -y nginx
    • 配置示例(/etc/nginx/conf.d/your_app.conf)
      • server {
        • listen 80;
        • server_name your_domain.com;
        • location / {
          • proxy_pass http://127.0.0.1:8080;
          • proxy_set_header Host $host;
          • proxy_set_header X-Real-IP $remote_addr;
          • proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          • proxy_set_header X-Forwarded-Proto $scheme;
        • }
      • }
    • 启用 HTTPS(推荐 Certbot 获取 Let’s Encrypt 证书)
  • 可选:若需更高性能与可观测性,可考虑基于 Pingora 构建反向代理/网关层

0