我正在使用帶有 Spring Boot 的 Java 8。如何實作以下場景的重試邏輯?
- 我將為資料庫生成一個隨機密鑰。
- 查詢該密鑰的資料庫,如果存在,請使用新密鑰重試。
- 使用新生成的密鑰持久化資料。
示例代碼:
int attempts = 1;
while (attempts <= PRESCRIBED_ATTEMPTS) {
String key = generateSomeRandomAlphaNum();
Future<String> resultFromDb = someRepository.getById(key);
resultFromDb.onSuccess(
result -> {
// since the key is already present
// retry here
Future<String> newAttempt = someRepository.getById(key);
attempts ;
}
);
}
我使用的是 Couchbase,所以這里的關鍵基本上是參考檔案。
uj5u.com熱心網友回復:
你的方法不正確。主鍵生成是 DB 而不是你的責任。因此,當您想要插入新物件時,您的 Entity 應該以這樣的方式正確注釋,以便 DB 為您生成有保證的唯一 ID。要了解它是如何完成的,請參閱這篇文章:Hibernate/JPA 中的識別符號概述。但是,一般來說,如果您想自己生成一些唯一 ID 用于任何目的,那么您應該創建自己的生成器來負責創建唯一 ID。如果您需要在正在運行的程式范圍內提供唯一的 id,那么最簡單的方法是使用AtomicLong類,并在每次需要新 ID 時增加它。如果要創建全球唯一 ID,請使用UUID類
uj5u.com熱心網友回復:
我做了以下靜態測驗,只做了一個小的改動。最重要的是while回圈。請注意使用 0 而不是 1 初始化嘗試。推薦使用駝峰式表示法(PRESCRIBED_ATTEMPTS-> 規定嘗試)
注意:這個解決方案是同步的,你可以通過實作一個未來的回呼來使這個函式異步
public class DemoApplication {
private static int random = 0;
public static int generateSomeRandomAlphaNum() {
return random ;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication2.class, args);
int attempts = 0; // 0 because you didnt had an attempt yet. 1 predicts you had one already.
int predscribedAttempts= 10;
int key = generateSomeRandomAlphaNum();
System.out.println("key: " key);
while (key != 7 && attempts <= predscribedAttempts) {
key = generateSomeRandomAlphaNum();
System.out.println("key: " key);
attempts ;
}
//finished within x attempts
System.out.println("finished within " attempts " attempts");
}
}
使用您的代碼,它看起來像:
public static void main(String[] args) {
SpringApplication.run(DemoApplication2.class, args);
int attempts = 0;
int predscribedAttempts= 10;
Future<String> resultFromDb = someRepository.getById(key);
while (!resultFromDb.isEmpty() && attempts <= predscribedAttempts) {
resultFromDb = someRepository.getById(key);
attempts ;
}
//finished
}
uj5u.com熱心網友回復:
建議使用Resilience4j 庫以遵守 DRY 原則
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436531.html
下一篇:瀏覽器多標簽會話問題
