首发于Enaium的个人博客
前言
Gradle是一个非常优秀的构建工具,但用过Maven的人都知道,Maven可以设置镜像,加速下载速度,而Gradle却没有这个功能。因为Gradle没有Maven这么死板的概念,在Gradle中大部分功能都是通过脚本实现的,所以我们可以通过脚本来实现镜像的功能。
首先需要了解一下什么是Initialization scripts,Initialization scripts是Gradle的初始化脚本,它可以在Gradle启动时执行,Gradle会在执行构建之前执行初始化脚本,也就是说我们可以在这个时候编写替换仓库地址的脚本,这样就可以实现镜像的功能。
脚本
首先我们需要再用户目录下的.gradle的目录下创建一个init.gradle.kts文件,然后在这个文件中编写脚本。
首先使用apply给脚本添加一个EnterpriseRepositoryPlugin插件,之后编写一个类实现Plugin接口,然后我们在apply方法中编写替换仓库地址的逻辑。
kotlin
apply<EnterpriseRepositoryPlugin>()
class EnterpriseRepositoryPlugin : Plugin<Gradle> {
override fun apply(gradle: Gradle) {
}
}
首先我们创建一个派生类,在这个派生类中定义一些常量,这些常量是我们要替换的仓库地址。
kotlin
companion object {
const val CENTRAL = "https://maven.aliyun.com/repository/central"
const val GRADLE_PLUGIN = "https://maven.aliyun.com/repository/gradle-plugin"
}
之后在这里使用gradle.settingsEvaluated方法,这个方法会在settings.gradle文件被解析之后执行,我们可以在这个方法中编写替换插件仓库地址的逻辑。
kotlin
gradle.settingsEvaluated {
pluginManagement {
repositories {
all {
if (this is MavenArtifactRepository) {
val url = this.url.toString()
if (url.startsWith("https://repo1.maven.org/maven2") || url.startsWith("https://repo.maven.apache.org/maven2")) {
this.setUrl(CENTRAL)
}
if (url.startsWith("https://plugins.gradle.org/m2")) {
this.setUrl(GRADLE_PLUGIN)
}
}
}
}
}
}
在完成插件的仓库地址替换之后,我们还需要替换项目的仓库地址,逻辑和替换插件的仓库地址一样。
kotlin
gradle.allprojects {
repositories {
all {
if (this is MavenArtifactRepository) {
val url = this.url.toString()
if (url.startsWith("https://repo1.maven.org/maven2") || url.startsWith("https://repo.maven.apache.org/maven2")) {
this.setUrl(CENTRAL)
}
if (url.startsWith("https://plugins.gradle.org/m2")) {
this.setUrl(GRADLE_PLUGIN)
}
}
}
}
}
这样完成之后,我们就可以飞快的下载项目中的插件和依赖了。
kotlin
apply<EnterpriseRepositoryPlugin>()
class EnterpriseRepositoryPlugin : Plugin<Gradle> {
companion object {
const val CENTRAL = "https://maven.aliyun.com/repository/central"
const val GRADLE_PLUGIN = "https://maven.aliyun.com/repository/gradle-plugin"
}
override fun apply(gradle: Gradle) {
gradle.settingsEvaluated {
pluginManagement {
repositories {
all {
if (this is MavenArtifactRepository) {
val url = this.url.toString()
if (url.startsWith("https://repo1.maven.org/maven2") || url.startsWith("https://repo.maven.apache.org/maven2")) {
this.setUrl(CENTRAL)
}
if (url.startsWith("https://plugins.gradle.org/m2")) {
this.setUrl(GRADLE_PLUGIN)
}
}
}
}
}
}
gradle.allprojects {
repositories {
all {
if (this is MavenArtifactRepository) {
val url = this.url.toString()
if (url.startsWith("https://repo1.maven.org/maven2") || url.startsWith("https://repo.maven.apache.org/maven2")) {
this.setUrl(CENTRAL)
}
if (url.startsWith("https://plugins.gradle.org/m2")) {
this.setUrl(GRADLE_PLUGIN)
}
}
}
}
}
}
}