2015-06-08 77 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中成功完成,也不會更新爲完成。 –

相關問題