Java 每一小时同步一次值



我有一个计算每小时货币换算的类。下面提供了该类,

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注释该方法,并在调用之间提供一些固定的时间。在这里,您可以找到使用示例。还记得用@EnableScheduling注释一些配置类。在您的情况下,您可以使用 cron:

@Scheduled(cron = "0 */1 * * *")

执行所需操作的最佳方法是使用@Scheduled。请参阅此链接,例如在春季。

长话短说 - 您可以使用@Scheduled注释方法,它将根据提供的规则执行。您应该将结果放在数据库中,在 REST 服务中只获取最后一个结果,或者如果您需要历史数据,则更多。

最新更新