每隔一小时就有一次Java Sync值

问题描述 投票:1回答:2

我有一个班级来计算每小时的货币换算次数。课程如下,

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同步。最好的方法是什么?

谢谢。

PS

我的意思是什么是每小时调用这个方法CurrencyUtilities.getConvertionRates()的最好方法?

java spring rest curl synchronization
2个回答
1
投票

您可以使用@Scheduled注释该方法,并在invokation之间提供一些固定的时间。 Here你可以找到用法的例子。还记得用@EnableScheduling注释一些配置类。在您的情况下,您可以使用cron:

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

1
投票

做你需要的最好的方法是使用@Scheduled。例如,在Spring中查看THIS链接。

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

© www.soinside.com 2019 - 2024. All rights reserved.