【问题标题】:How to call java function in Jenkinsfile using Pipeline plugin in Jenkins如何使用 Jenkins 中的 Pipeline 插件在 Jenkinsfile 中调用 java 函数
【发布时间】:2017-03-14 09:13:45
【问题描述】:

我在 jenkins 中使用管道插件。我的JenkinsfilenumToEcho =1,2,3,4 但我想调用Test.myNumbers() 来获取值列表。

  1. 如何在 Jenkinsfile 中调用 myNumbers() java 函数?
  2. 或者我是否需要一个单独的 groovy 脚本文件,并且我应该将该文件放在具有 Test 类的 java jar 中?

我的 Jenkins 文件:

def numToEcho = [1,2,3,4] 

def stepsForParallel = [:]

for (int i = 0; i < numToEcho.size(); i++) {
def s = numToEcho.get(i)
    def stepName = "echoing ${s}"

    stepsForParallel[stepName] = transformIntoStep(s)
}
parallel stepsForParallel

def transformIntoStep(inputNum) {
    return {
        node {
            echo inputNum
        }
    }
}



import com.sample.pipeline.jenkins
public class Test{

public ArrayList<Integer> myNumbers()    {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
 }
}

【问题讨论】:

    标签: jenkins plugins jenkins-pipeline


    【解决方案1】:

    您可以在 Groovy 文件中编写逻辑,您可以将其保存在 Git 存储库、Pipeline Shared Library 或其他地方。

    例如,如果您的存储库中有文件 utils.groovy

    List<Integer> myNumbers() {
      return [1, 2, 3, 4, 5]
    }
    return this
    

    在您的Jenkinsfile 中,您可以通过load step 像这样使用它:

    def utils
    node {
      // Check out repository with utils.groovy
      git 'https://github.com/…/my-repo.git'
    
      // Load definitions from repo
      utils = load 'utils.groovy'
    }
    
    // Execute utility method
    def numbers = utils.myNumbers()
    
    // Do stuff with `numbers`…
    

    或者,您可以检查您的 Java 代码并运行它,然后捕获输出。然后,您可以将其解析为列表,或稍后在管道中需要的任何数据结构。例如:

    node {
      // Check out and build the Java tool  
      git 'https://github.com/…/some-java-tools.git'
      sh './gradlew assemble'
    
      // Run the compiled Java tool
      def output = sh script: 'java -jar build/output/my-tool.jar', returnStdout: true
    
      // Do some parsing in Groovy to turn the output into a list
      def numbers = parseOutput(output)
    
      // Do stuff with `numbers`…
    }
    

    【讨论】:

    • 谢谢..这很有帮助..实际上问题是,我不能在 .groovy 文件中编写该函数,它必须是一个 java 文件。实际的 java 函数将检索数据(值列表)来自泰坦图形数据库..我无法在.groovy文件中编写该函数..所以我如何从Jenkinsfile或groovyscript调用java方法..
    • 在 Jenkinsfile: node { sh 'java jar titanRead.jar' echo inputNum } 上面的部分是并行部分..现在这个并行执行的数量将取决于列表大小(在上面的程序中列表大小为 5。所以时间会从 Titan 读取)。该列表还需要使用 java 函数从 titan db 获取。
    • 嗯,你可以在 Jenkins 中运行任何东西,这样你就可以运行你的 Java 程序并解析它的输出。我已经更新了答案以包含一个示例。
    • 我按照您的步骤操作,它正在工作..非常感谢您..:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    相关资源
    最近更新 更多