如何修复 Jenkins 工作流程构建期间的 NotSerializableException 错误?

How to fix NotSerializableException error during Jenkins workflow build?

当我在 Jenkins 工作流程(Jenkins 1.609.1,工作流程 1.8)上 运行 以下代码时,我收到 'NotSerializableException' 错误(也在下方)。 但是,如果我将 "build job" 移到 "for" 范围之外,它就可以正常工作(作业已激活)。任何想法为什么会出现这种行为?

node('master') { 
ws('/opt/test) {
def file = "/ot.property"
def line = readFile (file)
def resultList = line.tokenize()
for(item in resultList )
  {
build job: 'testjob_1'
   }
 }
}

出现错误:

Running: End of Workflow 
java.io.NotSerializableException: java.util.ArrayList$Itr  
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)  


.....

我认为这是因为它在到达 build job 步骤后立即尝试在 resultList 上序列化不可序列化的 item 迭代器。有关使用不可序列化变量的指南,请参阅此处:

https://github.com/jenkinsci/workflow-plugin/blob/master/TUTORIAL.md#serialization-of-local-variables

作为使用工作流插件安全迭代的解决方法,您需要使用 C 风格的循环。试试这个:

for ( int i = 0; i < resultList.size; i++ ) {
  etc...

根据CloudBees Platform Help page

By design the pipeline can only keep records of Serializable objects. If you still need to keep an intermediate variable with a non serializable object, you need to hide it into a method and annotate this method with @NonCPS.

因此,您应该使用 @NonCPS 辅助方法将代码转换为函数。

相关的 Jenkins 错误:JENKINS-27421