缓存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 的内容将经过哈希处理,以生成动态缓存密钥。 这将确保每次修改文件时,都会生成新的缓存密钥。
variables:
NUGET_PACKAGES: $(Pipeline.Workspace)/.nuget/packages
- task: Cache@2
displayName: Cache
inputs:
key: 'nuget | "$(Agent.OS)" | **/packages.lock.json,!**/bin/**,!**/obj/**'
path: '$(NUGET_PACKAGES)'
cacheHitVar: 'CACHE_RESTORED'
还原缓存
仅当变量为 false 时, CACHE_RESTORED 此任务才会运行。
- task: NuGetCommand@2
condition: ne(variables.CACHE_RESTORED, true)
inputs:
command: 'restore'
restoreSolution: '**/*.sln'
性能比较
管道缓存是加快管道执行速度的好方法。 下面是两个不同管道的并行性能比较。 在向右 () 添加缓存任务之前,还原任务大约需要 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/**'
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)'