我必須在 Springboot java 應用程式中的多個位置呼叫外部 api。外部 api 將始終回傳一個靜態常量字串值。
請在下面找到示例代碼以更好地解釋我的意圖以及我希望在一天結束時實作的目標
我的示例代碼使用 RestTemplate 呼叫外部 api 來檢索字串值。
ResponseEntity<String> result = new RestTemplate().exchange("http://localhost:7070/api/test/{id}",
HttpMethod.GET, entity, String.class, id);
JSONObject jsonResponse = new JSONObject(result.getBody());
String reqVal = jsonResponse.getString("reqKey");
現在,我的目的是讓這個 String 在應用程式中全域可用,以避免多次呼叫這個 api。
我正在考慮在應用程式啟動時呼叫這個外部 api 并在 Springboot 應用程式背景關系中設定這個 String 值,以便可以從應用程式的任何地方檢索它。
誰能建議,我怎樣才能達到我的上述要求?或者還有其他更好的選擇嗎?
提前致謝!
uj5u.com熱心網友回復:
我會將它存盤在呼叫外部 API 的 Spring 管理 Bean 的記憶體中,然后允許任何其他 Spring 管理 Bean 從該組件中獲取它。
@Service
public class ThirdPartyServiceClient implements ApplicationListener<ContextRefreshedEvent> {
private String reqKey = null;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
(...)
ResponseEntity<String> result = new RestTemplate()
.exchange("http://localhost:7070/api/test/{id}", HttpMethod.GET, entity, String.class, id);
JSONObject jsonResponse = new JSONObject(result.getBody());
this.reqKey = jsonResponse.getString("reqKey");
}
public String getKey() {
return reqKey;
}
}
現在,您只需要ThirdPartyServiceClient在任何其他 bean 中注入Spring 管理的 bean 即可呼叫getKey()方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354962.html
