我有一個名為 getCustomerCount() 的方法,它呼叫資料庫以根據商店獲取客戶計數,如下所示。
public int getCustomerCount(String storeName) {
return repository.getCustomerCount(storeName);
}
我需要從其他方法多次呼叫上述方法,所以我可以使用實體變數在第一次呼叫此方法時設定客戶計數,然后重用該變數而不是呼叫此方法并每次呼叫資料庫時間?我可以做這樣的事情:
private int customerCount;
public int getCustomerCount(String storeName) {
int count = repository.getCustomerCount(storeName);
customerCount = count;
return count;
}
public void processCustomerData(String storeName) {
getCustomerCount(storeName);
// Based on customer count, add business logic
sendEmail(customerList);
}
public void sendEmail(List<Customers> customers) {
// get customer count and set email count to the number of customers in the system.
int emailCount = 0;
emailCount = customerCount;
}
當多個請求通過rest api同時執行時,這會是一個問題嗎?像這樣使用實體變數有什么優缺點嗎?如果有比使用實體變數更好的方法,請提出建議。我需要為每個請求執行查詢,因此單例可能不適用于這種情況。謝謝你。
uj5u.com熱心網友回復:
您可以嘗試使用單例設計模式來解決您的特定問題
請參閱此鏈接:https ://www.gofpatterns.com/creational/patterns/singleton-pattern.php
uj5u.com熱心網友回復:
我假設您共享的上述代碼是customerService. SpringBoot 是單例的,因此在 SpringBoot 物件中包含全域變數(如果它們不是常量)不是一個好習慣。
@Service
private CustomerService customerService;
int customerCount = customerService.getCustomerCount();
customerService.processCustomer(customerCount); // you should pass customerCount
你也應該改變方法,因為如果大小可以不同,sendEmail它應該將 customerCount 作為引數customerscustomerCount
public void sendEmail(List<Customers> customers, int customerCount)
uj5u.com熱心網友回復:
如果您不希望該方法每次都命中資料庫,則應使用 Integer 包裝類并將計數存盤在映射中:
private Map<String, Integer> customerCountMap = new HashMap();
public int getCustomerCount(String storeName) {
if(customerCountMap.get(storeName) == null) {
// you will probably need to pass the store name to the repository...
customerCountMap.put(storeName, repository.getCustomerCount(storeName));
}
return customerCountMap.get(storeName);
}
您仍然需要更新插入和洗掉的計數。所以你最終可能會使用 Spring快取(或者你可以使用老式的觀察者模式)。
sendEmail() 方法仍然沒有意義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424562.html
上一篇:@Index注釋導致“此注釋不適用于目標'帶有支持欄位的成員屬性'”
下一篇:訪問當前PowerShell實體
