配置管理 #

Rocket使用灵活的配置系统,支持多种配置方式和环境管理。本节将介绍如何管理Rocket应用配置。

配置文件 #

Rocket.toml #

toml
[default]
address = "127.0.0.1"
port = 8000
workers = 4
keep_alive = 5
log_level = "normal"
secret_key = "your-secret-key-here"

[debug]
address = "127.0.0.1"
port = 8000
log_level = "debug"

[release]
address = "0.0.0.0"
port = 80
workers = 12
log_level = "critical"

配置项说明 #

配置项 类型 说明 默认值
address string 监听地址 127.0.0.1
port int 监听端口 8000
workers int 工作线程数 CPU核心数
keep_alive int Keep-alive超时(秒) 5
log_level string 日志级别 normal
secret_key string 加密密钥 随机生成
limits table 请求大小限制 -

环境配置 #

环境类型 #

环境 说明
debug 开发环境
release 生产环境
default 默认配置

设置环境 #

bash
ROCKET_PROFILE=release cargo run

环境变量覆盖 #

bash
export ROCKET_ADDRESS=0.0.0.0
export ROCKET_PORT=8080
export ROCKET_LOG_LEVEL=debug

自定义配置 #

定义配置结构 #

rust
use rocket::fairing::AdHoc;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct AppConfig {
    app_name: String,
    version: String,
    api_key: String,
    max_items: usize,
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(AdHoc::config::<AppConfig>())
        .mount("/", routes![index])
}

使用配置 #

rust
use rocket::State;

#[get("/")]
fn index(config: &State<AppConfig>) -> String {
    format!("{} v{}", config.app_name, config.version)
}

Rocket.toml自定义配置 #

toml
[default]
app_name = "My Rocket App"
version = "1.0.0"
api_key = "your-api-key"
max_items = 100

数据库配置 #

数据库连接配置 #

toml
[default.databases.my_db]
url = "postgres://user:password@localhost/mydb"
pool_size = 10
timeout = 5

多数据库配置 #

toml
[default.databases.primary]
url = "postgres://user:password@primary-db/mydb"

[default.databases.replica]
url = "postgres://user:password@replica-db/mydb"

[default.databases.cache]
url = "redis://localhost:6379"

运行时配置 #

代码中配置 #

rust
use rocket::Config;
use rocket::data::{Limits, ByteUnit};

#[launch]
fn rocket() -> _ {
    let config = Config::figment()
        .merge(("port", 8080))
        .merge(("limits", Limits::new()
            .limit("json", ByteUnit::Megabyte(5))
            .limit("file", ByteUnit::Megabyte(20))
        ));
    
    rocket::custom(config)
        .mount("/", routes![index])
}

条件配置 #

rust
use rocket::Config;

fn get_config() -> Config {
    if cfg!(debug_assertions) {
        Config::debug_default()
    } else {
        Config::release_default()
    }
}

#[launch]
fn rocket() -> _ {
    rocket::custom(get_config())
        .mount("/", routes![index])
}

密钥管理 #

生成密钥 #

bash
openssl rand -base64 32

配置密钥 #

toml
[default]
secret_key = "your-generated-secret-key"

环境变量 #

bash
export ROCKET_SECRET_KEY="your-secret-key"

日志配置 #

日志级别 #

级别 说明
off 关闭日志
critical 仅严重错误
normal 正常日志
debug 调试日志

配置日志 #

toml
[debug]
log_level = "debug"

[release]
log_level = "critical"

完整示例 #

rust
#[macro_use] extern crate rocket;

use rocket::fairing::AdHoc;
use rocket::State;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct AppConfig {
    app_name: String,
    version: String,
    debug: bool,
}

#[get("/")]
fn index(config: &State<AppConfig>) -> String {
    format!("{} v{} (debug: {})", 
        config.app_name, 
        config.version, 
        config.debug
    )
}

#[get("/config")]
fn show_config(config: &State<AppConfig>) -> String {
    format!("{:?}", config)
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(AdHoc::config::<AppConfig>())
        .mount("/", routes![index, show_config])
}

Rocket.toml:

toml
[default]
app_name = "Rocket Demo"
version = "1.0.0"
debug = false
address = "127.0.0.1"
port = 8000

[debug]
debug = true
log_level = "debug"

[release]
debug = false
address = "0.0.0.0"
port = 80
log_level = "critical"

下一步 #

掌握了配置管理后,让我们继续学习 测试,了解如何测试Rocket应用。

最后更新:2026-03-28