2015-06-08 103 views
2

我正在使用以下代码将目标池添加到java计算引擎中,使用Google Compute Engine Java API什么是检测Java API调用是否成功完成的最佳方法

Operation operation = compute.targetPools().insert(PROJECT_ID, REGION_NAME, targetPool).execute(); 

我需要确保在执行下一行之前成功添加目标池。在Google Compute Engine API中做什么最好的方法是什么?

+0

你试过我的建议,检查操作状态? – daniel

+0

嗨,是的,我现在尝试。但似乎更新的操作状态有所改变。它总是说未决。但我可以看到目标池在GCE中创建。 –

回答

2

你需要等待,直到操作将在状态DONE,然后检查它是否没有错误。为了做到这一点,你需要使用compute来查询操作。“operations”()。get() - 我将操作放在引号中,因为有三种类型的操作:全局,区域和区域,每个操作有它自己的服务:globalOperations(),regionOperations()和zoneOperations()。由于targetPools是区域性资源,所以insert创建的操作也是区域性的,因此您需要使用compute()。regionOperations()。get()。代码:

while (!operation.getStatus().equals("DONE")) { 
    RegionOperations.Get getOperation = compute.regionOperations().get(
       PROJECT_ID, REGION_NAME, operation.getName()); 
    operation = getOperation.execute(); 
} 
if (operation.getError() == null) { 
    // targetPools has been successfully created 
} 
+0

谢谢你的回答。这是对的。我检查了本地操作对象的状态。这就是为什么它总是显示'PENDING'。 –

0

您是否尝试过使用try/catch块? 你可以这样做:

try 
{ 
    Operation operation = compute.targetPools().insert(PROJECT_ID, REGION_NAME, targetPool).execute(); 
} 
catch(Exception ex) 
{ 
    //Error handling stuff 
} 

希望帮助:)

+0

谢谢你的回答。但是我已经尝试过了,但是通过使用try catch块来判断操作是否成功是不可能的 –

1

一种可能性是检查状态

while(!operation.getStatus().equals("DONE")) { 
    //wait 
    System.out.println("Progress: " + operation.getProgress()); 
} 
    // Check if Success 
if(operation.getError() != null) { 
    // Handle Error 
} else { 
    // Succeed with Program 
} 
+0

看起来这是正确的。但操作状态永远不会更新到完成。我认为这可能是GCE API中的一个错误。 –

+0

更新我的答案,因为operation.getStatus()返回一个字符串,而不是一个枚举,因为我认为,所以比较equals(“完成”)应该工作。顺便说一句。什么是operation.getProgress()显示? getStatus()是否总是“持续”? – daniel

+0

嗨丹尼尔, 是的,它显示总是悬而未决。即使资源在GCE中成功完成,也不会更新为完成。 –

相关问题