快取 NuGet 套件

Azure DevOps Services

透過管線快取,您可以快取相依性,以便在稍後執行時重複使用,以減少建置時間。 在本文中,您將瞭解如何使用快取 工作 來快取和還原 NuGet 套件。

鎖定相依性

若要設定快取工作,我們必須先鎖定專案的相依性,並建立 package.lock.json 檔案。 我們將使用此檔案內容的雜湊來產生快取的唯一索引鍵。

若要鎖定專案的相依性,請將csproj檔案中的RestorePackagesWithLockFile屬性設定為true。 NuGet 還原會在專案的根目錄中產生鎖定檔案 packages.lock.json 。 請務必將 packages.lock.json 檔案簽入原始程式碼。

<PropertyGroup>
  <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>

快取 NuGet 套件

我們需要建立管線變數,以指向執行管線之代理程式上的套件位置。

在此範例中, packages.lock.json 的內容會經過雜湊處理,以產生動態快取索引鍵。 這可確保每次修改檔案時,都會產生新的快取索引鍵。

顯示如何在 Azure Pipelines 中產生快取金鑰的螢幕擷取畫面。

variables:
  NUGET_PACKAGES: $(Pipeline.Workspace)/.nuget/packages

- task: Cache@2
  displayName: Cache
  inputs:
    key: 'nuget | "$(Agent.OS)" | **/packages.lock.json,!**/bin/**,!**/obj/**'
    restoreKeys: |
       nuget | "$(Agent.OS)"
       nuget
    path: '$(NUGET_PACKAGES)'
    cacheHitVar: 'CACHE_RESTORED'

注意

快取是不可變的,一旦建立快取,就無法修改其內容。

還原快取

只有在變數為 false 時, CACHE_RESTORED 才會執行此工作。

- task: NuGetCommand@2
  condition: ne(variables.CACHE_RESTORED, true)
  inputs:
    command: 'restore'
    restoreSolution: '**/*.sln'

如果您在建置工作期間遇到錯誤訊息 「project.assets.json」,您可以從還原工作中移除條件 condition: ne(variables.CACHE_RESTORED, true) 來解決此問題。 如此一來,將會執行 restore 命令,並產生 project.assets.json 檔案。 還原工作不會下載已存在於對應資料夾中的套件。

注意

管線可以包含一或多個快取工作,而相同管線內的作業和工作可以存取和共用相同的快取。

表現比較

管線快取是加速管線執行的絕佳方式。 以下是兩個不同管線的並存效能比較。 在) 新增快取工作 (之前,還原工作大約需要 41 秒。 我們已將快取工作新增至第二個管線 (左側) ,並將還原工作設定為在遇到快取遺漏時執行。 在此情況下,還原工作需要 8 秒才能完成。

顯示管線效能的螢幕擷取畫面,其中包含不含快取的管線效能。

以下是完整的 YAML 管線以供參考:

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
  NUGET_PACKAGES: $(Pipeline.Workspace)/.nuget/packages

steps:
- task: NuGetToolInstaller@1
  displayName: 'NuGet tool installer'

- task: Cache@2
  displayName: 'NuGet Cache'
  inputs:
    key: 'nuget | "$(Agent.OS)" | **/packages.lock.json,!**/bin/**,!**/obj/**'
    restoreKeys: |
       nuget | "$(Agent.OS)"
       nuget
    path: '$(NUGET_PACKAGES)'
    cacheHitVar: 'CACHE_RESTORED'

- task: NuGetCommand@2
  displayName: 'NuGet restore'
  condition: ne(variables.CACHE_RESTORED, true)
  inputs:
    command: 'restore'
    restoreSolution: '$(solution)'

- task: VSBuild@1
  displayName: 'Visual Studio Build'
  inputs:
    solution: '$(solution)'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'