背景
我們在寫 Jenkins 的 Shared Library 時,有時候需要參考外部的一些 jar 包,比如 maven central 的一些 lib 等,
具體到我們的例子,需要參考 Gson 做 json 序列化,
問題
我們的 Shared Library 中有如下代碼,用到了 Gson:
import com.google.gson.Gson
/**
* @author wxweven
*/
class JsonUtils {
static final Gson GSON = new Gson()
static String toJson(User user) {
return GSON.toJson(user)
}
}
但是在執行的時候,Jenkins 報錯:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: JsonUtils.groovy: 3: unable to resolve class com.google.gson.Gson @ line 3, column 1. import com.google.gson.Gson
原因就是 Jenkins 無法找到 Gson 依賴,因為 Jenkins 系統默認是沒有 Gson jar 包的,
添加 Grab 支持
那么怎么給 Jenkins 的 Shared Library 添加第三方包支持呢?
Jenkins 官方檔案中有說明:Using third-party libraries,
添加 @Grab 注解即可,示例如下:
@Grab('org.apache.commons:commons-math3:3.4.1')
import org.apache.commons.math3.primes.Primes
void parallelize(int count) {
if (!Primes.isPrime(count)) {
error "${count} was not prime"
}
// …
}
結合我們的代碼,添加 @Grab 注解后的版本如下:
@Grab('com.google.code.gson:gson:2.8.6')
import com.google.gson.Gson
/**
* @author wxweven
*/
class JsonUtils {
public static final Gson GSON = new Gson()
static String toJson(User user) {
return GSON.toJson(user)
}
}
這樣就可以給 Jenkins 中添加 Gson 的 jar 包支持了,
Grab 的語法,跟 maven 的 pom 比較類似,默認的格式是:groupId:artifactId:version,
關于 Grab 的更多用法,請參考:官方檔案
默認下載的 jar 包,會快取在 Master 節點的 ~/.groovy/grapes/ 目錄下,
結束語
我是梅小西,最近在某東南亞電商公司做 DevOps 的相關事情,從本期開始,將陸續分享基于 Jenkins 的 CI/CD 作業流,包括 Jenkins On k8s 等,
如果你對 Java 或者 Jenkins 等感興趣,歡迎與我聯系,微信:wxweven(備注 DevOps)
我是梅小西,最近在某東南亞電商公司做 DevOps 的相關事情,從本期開始,將陸續分享基于 Jenkins 的 CI/CD 作業流,包括 Jenkins On k8s 等,
如果你對 Java 或者 Jenkins 等感興趣,歡迎與我聯系,微信:wxweven(備注 DevOps)
本文由博客群發一文多發等運營工具平臺 OpenWrite 發布
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479208.html
標籤:Java
