Using Dependency Cache
Applicable Scenarios
When you need to cache dependency packages (npm, Maven, pip, Gradle, etc.) to speed up subsequent builds.
Prerequisites
- The cache directory path is confirmed.
- The version of the cache plugin used is confirmed (recommended v4).
- Understand the design principles of cache keys and restore-keys.
Quick Example
name: ci-with-cache
on:
push:
branches:
- main
jobs:
build:
runs-on: [ubuntu-latest, x64, small]
steps:
- uses: checkout
- name: Cache npm dependencies
uses: cache
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
- name: Install and test
run: |
npm ci
npm test
Configuration Description
Cache Plugin Parameters
steps:
- name: Cache dependencies
uses: cache
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
| Parameter | Required | Description |
|---|---|---|
path | Yes | The cache directory path, supports single or multiple paths |
key | Yes | The cache key, which directly restores the cache when there is an exact match |
restore-keys | No | A list of fallback restore keys for prefix matching, tried in order |
Cache Matching Mechanism
- First, try an exact match with
key. - If the exact match fails, try prefix matching in the order of
restore-keyslist. - Prefix matching restores the most recent cache with the same prefix.
- If all matches fail, the contents of
pathwill be saved as a new cache after the step is executed.
Multi-path Caching
steps:
- name: Cache multiple paths
uses: cache
with:
path: |
~/.npm
~/.cache/pip
node_modules
key: deps-${{ runner.os }}-${{ hashFiles('package-lock.json', 'requirements.txt') }}
Common Language Cache Examples
Node.js / npm
steps:
- name: Cache npm
uses: cache
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
- run: npm ci
Java / Maven
steps:
- name: Cache Maven
uses: cache
with:
path: ~/.m2/repository
key: maven-${{ runner.os }}-${{ hashFiles('**/pom.xml') }}
restore-keys: |
maven-${{ runner.os }}-
- run: mvn -B test
Java / Gradle
steps:
- name: Cache Gradle
uses: cache
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', 'gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- run: ./gradlew build
Python / pip
steps:
- name: Cache pip
uses: cache
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ hashFiles('requirements.txt') }}
restore-keys: |
pip-${{ runner.os }}-
- run: pip install -r requirements.txt
Go
steps:
- name: Cache Go modules
uses: cache
with:
path: ~/go/pkg/mod
key: go-${{ runner.os }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-${{ runner.os }}-
- run: go build ./...