プロファイルの最適化、LTO、コード生成ユニットをリリースします。メモリ アロケータ (jemalloc、mimalloc)。接続プーリング、リクエストのバッチ処理。スケーリング戦略、Rust によるマイクロサービス。
Rust: 基本から上級まで
パート 6: テスト、CI/CD、本番環境
xdev.asia
1. リリースプロファイルの最適化
# Cargo.toml
[profile.release]
opt-level = 3 # Maximum optimization
lto = "fat" # Link-Time Optimization — binary nhỏ hơn, nhanh hơn
codegen-units = 1 # Single codegen unit — tối ưu tốt hơn
strip = true # Strip debug symbols
panic = "abort" # Không unwind — binary nhỏ hơn
[profile.dev]
opt-level = 0
debug = true
# Custom profile
[profile.profiling]
inherits = "release"
debug = true # Debug symbols nhưng optimized
strip = false
# Build size comparison
cargo build --release
ls -la target/release/my-app # ~5MB (stripped, LTO)
# Analyze binary size
cargo install cargo-bloat
cargo bloat --release --crates
2. メモリ アロケータ
// jemalloc — tốt cho multi-threaded workloads
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
// mimalloc — tốt cho general purpose
// [dependencies]
// mimalloc = { version = "0.1", default-features = false }
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
| アロケータ | ユースケース | 長所 |
| システム (デフォルト) | 一般 | 余分な依存関係はありません |
| ジェマロック | 同時実行性の高いサーバー | 断片化とマルチスレッドを削減する |
| ミマロック | 一般的、遅延の影響を受けやすい | 高速、コンパクト、クロスプラットフォーム |
// Connection pooling
let pool = PgPoolOptions::new()
.max_connections(20)
.min_connections(5)
.max_lifetime(Duration::from_secs(1800))
.idle_timeout(Duration::from_secs(600))
.acquire_timeout(Duration::from_secs(5))
.connect(&database_url)
.await?;
// Request batching
use tokio::sync::mpsc;
use tokio::time::interval;
struct Batcher {
tx: mpsc::Sender<BatchItem>,
}
impl Batcher {
fn new(pool: PgPool) -> Self {
let (tx, mut rx) = mpsc::channel(1000);
tokio::spawn(async move {
let mut buffer = Vec::new();
let mut tick = interval(Duration::from_millis(100));
loop {
tokio::select! {
Some(item) = rx.recv() => {
buffer.push(item);
if buffer.len() >= 100 {
flush_batch(&pool, &mut buffer).await;
}
}
_ = tick.tick() => {
if !buffer.is_empty() {
flush_batch(&pool, &mut buffer).await;
}
}
}
}
});
Self { tx }
}
}
// String optimization — avoid allocation
fn process(input: &str) -> &str {
// Trả reference thay vì clone
input.trim()
}
// Cow — clone on write
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
4. 制作チェックリスト
| カテゴリ | アイテム |
| ビルドする | LTO 対応、単一コード生成ユニット、ストリップ済み |
| アロケータ | jemalloc または mimalloc |
| ロギング | トレース + JSON 形式 + RUST_LOG |
| メトリクス | プロメテウス + グラファナ |
| 健康 | /health エンドポイント、readiness/liveness |
| シャットダウン | 正常なシャットダウン (SIGTERM) |
| セキュリティ | 貨物監査、貨物拒否 |
| ドッカー | マルチステージ + ディストロレス/スクラッチ |
| DB | 接続プーリング、移行 |
| CI/CD | fmt、クリッピー、テスト、監査、ビルド |
シリーズ完結おめでとうございます Rust: 基本から上級まで! 🎉