我有一个计算每小时货币兑换的类(class)。下面提供了该类,
public class CurrencyUtilities {
public static String getCurrencyExchangeJsonData(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static Map<String, Double> getConvertionRates() {
/*
* https://openexchangerates.org/api/latest.json?app_id=50ef786fa73e4f0fb83e451a8e5b860a
* */
String s = "https://openexchangerates.org/api/latest.json?app_id=" + "50ef786fa73e4f0fb83e451a8e5b860a";
String response = null;
try {
response = getCurrencyExchangeJsonData(s);
} catch (Exception e) {
}
final JSONObject obj = new JSONObject(response.trim());
String rates = obj.get("rates").toString();
JSONObject jsonObj = new JSONObject(rates);
Iterator<String> keys = jsonObj.keys();
Map<String, Double> map = new HashMap<>();
double USD_TO_EUR = Double.parseDouble(jsonObj.get("EUR").toString());
map.put("USD", (1.0 / USD_TO_EUR));
while (keys.hasNext()) {
String key = keys.next();
double v = Double.parseDouble(jsonObj.get(key).toString());
map.put(key, (double) (v / USD_TO_EUR));
}
// for (Map.Entry<String, Double> entry : map.entrySet()) {
// System.out.println(entry.getKey() + " " + entry.getValue());
// }
return map;
}
}
在 API 中,我调用提供的值,
@RestController
@RequestMapping("/api/v1/users")
public class UserAPI {
static Map<String, Double> currencyMap = CurrencyUtilities.getConvertionRates();
// .....................................
// .....................................
}
我需要将每小时 currencyMap
的值与 openexchangerates.org
同步。最好的方法是什么?
谢谢。
附注
我的意思是每小时调用此方法 CurrencyUtilities.getConvertionRates()
的最佳方式是什么?
最佳答案
您可以使用@Scheduled
注释该方法,并在调用之间提供一些固定的时间。 Here您可以找到使用示例。还记得用@EnableScheduling
注释一些配置类。在你的情况下,你可以使用 cron:
@Scheduled(cron = "0 */1 * * *")
关于每一小时 Java 同步值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55645697/