管理 Java Cloud 用戶端程式庫的用戶端生命週期

用戶端程式庫執行個體可重複使用,且設計為長期存在。一般來說,應用程式會維護單一用戶端程式庫執行個體,而不是為每個要求建立程式庫。

以 Java-KMS 為例,下列程式碼片段顯示使用相同用戶端執行個體叫用的多項要求:

// Create one instance of KMS's KeyManagementServiceClient
KeyManagementServiceClient keyManagementServiceClient =
 KeyManagementServiceClient.create();
keyManagementServiceClient.listKeyRings();
keyManagementServiceClient.asymmetricSign();
keyManagementServiceClient.createCryptoKey();
// ... other code ...

// Create one instance of KMS's AutokeyClient
AutokeyClient autokeyClient = AutokeyClient.create();
autokeyClient.listKeyHandles();
autokeyClient.getKeyHandle();

關閉用戶端

管理用戶端生命週期的方式取決於用途和特定用戶端程式庫。舉例來說,如果您使用架構,請按照架構的客戶管理指南操作。雖然某些情境可能會使用 try-with-resources,但一般建議重複使用長期用戶端例項,以提高效率

在用戶端呼叫 close() 會嘗試有序關閉,並確保現有工作會繼續執行直到完成。客戶不會接受新工作。如果不關閉用戶端,資源會持續存在,應用程式也會發生記憶體洩漏問題。

以下範例使用 Java-KMS,並顯示用戶端已關閉:

KeyManagementServiceClient keyManagementServiceClient =
  KeyManagementServiceClient.create(keyManagementServiceSettings);
// ... other code ...
keyManagementServiceClient.close();

// For gRPC clients, it's recommended to call awaitTermination to ensure a
// graceful shutdown and avoid the following error message in the logs:
// ERROR i.g.i.ManagedChannelOrphanWrapper - *~*~*~ Channel ManagedChannelImpl
// was not shutdown properly!!! ~*~*~*
// java.lang.RuntimeException: ManagedChannel allocation site
// at io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference.<init>
keyManagementServiceClient.awaitTermination(DURATION, TimeUnit.SECONDS);

// Optionally include a shutdownNow() call after awaitTermination() to force
// close any lingering resources
keyManagementServiceClient.shutdownNow();

除了 close(),部分 Java 用戶端程式庫還會公開幾個相關方法,用於管理用戶端生命週期:

  • shutdown():相當於 close()
  • shutdownNow():立即啟動關機程序。停止所有正在執行的工作,不會等待工作完成。
  • isShutdown():如果背景工作已關閉,則會傳回 true
  • isTerminated():如果所有工作都在關機後完成,則傳回 true
  • awaitTermination():封鎖一段時間,直到關機後所有工作都完成為止。

多重客戶案件

在特定客戶使用案例中,可能需要多個並存的用戶端程式庫執行個體。如果要求必須傳送至多個不同的端點,主要用途就是使用多個用戶端。用戶端執行個體會連線至單一端點。如要連線至多個端點,請為每個端點建立用戶端。

潛在多重客戶風險

如果應用程式使用多個用戶端程式庫例項,可能會出現以下常見風險:

  • 記憶體流失的可能性增加。如果未正確關閉所有用戶端例項,資源就會持續存在。
  • 效能影響。初始化多個 gRPC 管道會產生效能成本,在效能敏感型應用程式中,這筆成本可能會累積。
  • 處理中的要求發生問題。如果要求仍在傳輸中,關閉用戶端可能會導致 RejectedExecutionException。請務必先完成要求,再關閉用戶端。