Featured image of post 使用快取加速 GitHub Actions CI/CD 工作流程Featured image of post 使用快取加速 GitHub Actions CI/CD 工作流程

使用快取加速 GitHub Actions CI/CD 工作流程

透過快取 npm 模組、pip 套件和 Cargo 建置目標來優化 GitHub Actions 建置步驟。

優化 CI/CD 工作流程時間直接影響開發人員的工作效率並降低計算費用。本文向您展示如何在 GitHub Actions 中整合依賴項緩存,幫助您縮短編譯和套件設定時間。

我們提供適用於 Node.js、Python 和 Rust 的 YAML 工作流程模板,以及確保最佳快取命中的最佳實務。


1. CI/CD中為什麼要快取依賴關係?

當 CI 代理程式在沒有快取的情況下啟動時,它會啟動一個乾淨的容器並從套件註冊表中取得每個相依性。這帶來了幾個缺點:

  1. 低效率的開發循環:開發人員在測試程式碼之前浪費寶貴的時間等待標準庫安裝。
  2. 網路風險:如果 npm、PyPI 或 crates.io 發生輕微停機,則您的建置會因外部網路問題而失敗。
  3. 執行成本:在私人儲存庫上,GitHub 按每活躍分鐘向您收費。更快的建置直接降低了營運成本。

快取允許管道在執行過程中重複使用下載的資源,使後續運行的執行速度提高 80%。


2. 主要語言的 YAML 模板

2026 年,GitHub 的預設語言設定操作包括內建快取支持,使配置變得簡單。

1)Node.js(npm / pnpm / 紗線)

配置 actions/setup-node 下的 cache 屬性:

name: Node.js CI

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm' # Supports npm, yarn, or pnpm

      - name: Install Packages
        run: npm ci

      - name: Run Tests
        run: npm test

2)Python(點子/詩)

對於 Python 環境,使用 actions/setup-python 中的 cache 鍵啟用快取:

name: Python Test Runner

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip' # Supports pip, poetry, or pipenv
      - name: Install Dependencies
        run: pip install -r requirements.txt
      - name: Run Linter
        run: flake8 .

3) 生鏽(貨物)

Rust 編譯是出了名的慢。若要快取 Cargo 依賴項和中間建置工件(/target 目錄),請使用社群標準 swatinem/rust-cache

name: Rust CI

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup Rust compiler
        uses: actions/setup-rust@v1
      - name: Configure Cargo Cache
        uses: swatinem/rust-cache@v2
      - name: Execute Tests
        run: cargo test

3. 自訂快取和故障排除

對於預設操作未處理的資料夾,請使用 actions/cache 手動定義它們:

- name: Cache Custom Files
  uses: actions/cache@v4
  with:
    path: ~/.my-custom-cache
    key: ${{ runner.os }}-custom-${{ hashFiles('**/lockfile.json') }}
    restore-keys: |
      ${{ runner.os }}-custom-
  • key:快取的唯一識別碼。 hashFiles 函數建立鎖定檔案的雜湊值(package-lock.jsonCargo.lock 等)。當鎖定檔案變更時,舊的快取將失效並建立新的快取。
  • restore-keys:如果未找到確切的快取命中,則傳回秋季的前綴鍵的有序清單。

防止快取未命中

  1. 提交鎖定檔案:確保在 Git 中追蹤鎖定檔案。如果沒有它們,哈希值就會波動,導致頻繁的快取未命中。
  2. 追蹤快取大小:GitHub 將每個儲存庫的快取儲存限制為 10GB。一旦超過此限制,GitHub 會自動逐出較舊的快取。從快取路徑中排除不必要的建置工件。

4. 總結

配置操作快取是優化軟體管道最簡單的方法之一。實施這些變更可以每週為您的團隊節省數小時的等待時間。立即驗證您的 YAML 工作流程並整合快取。