| | |
| | | } |
| | | } |
| | | |
| | | public String doGet(String pid) { |
| | | // 从配置中获取 API URL,并拼接 key |
| | | private static String lastResult = null; |
| | | private static long lastExecuteTime = 0; |
| | | private static final long MIN_INTERVAL_MS = 3000; |
| | | private static final Object cacheLock = new Object(); |
| | | |
| | | public static String doGet(String pid) { |
| | | long currentTime = System.currentTimeMillis(); |
| | | |
| | | // 第一次快速检查(不加锁) |
| | | if (lastResult != null && (currentTime - lastExecuteTime) < MIN_INTERVAL_MS) { |
| | | return lastResult; |
| | | } |
| | | |
| | | // 同步块内再次检查并执行 |
| | | synchronized (cacheLock) { |
| | | currentTime = System.currentTimeMillis(); |
| | | if (lastResult != null && (currentTime - lastExecuteTime) < MIN_INTERVAL_MS) { |
| | | return lastResult; |
| | | } |
| | | |
| | | // 执行POST请求 |
| | | String newResult = doActualPost(pid); |
| | | |
| | | // 更新缓存 |
| | | lastResult = newResult; |
| | | lastExecuteTime = System.currentTimeMillis(); |
| | | |
| | | return newResult; |
| | | } |
| | | } |
| | | |
| | | private static String doActualPost(String pid) { |
| | | String apiUrl = PropertiesUtil.getProperty("JS_IN_HTTP_URL") + "stock?key=" + PropertiesUtil.getProperty("JS_IN_KEY"); |
| | | String result = null; |
| | | |
| | | try { |
| | | Thread.sleep(3000); |
| | | URL url = new URL(apiUrl); |
| | | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| | | |
| | | // 设置请求方法为 POST |
| | | connection.setRequestMethod("POST"); |
| | | // 设置请求头 |
| | | connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); |
| | | connection.setDoOutput(true); // 允许向连接输出 |
| | | connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); |
| | | connection.setDoOutput(true); |
| | | connection.setConnectTimeout(5000); |
| | | connection.setReadTimeout(10000); |
| | | |
| | | // 构建 POST 数据 |
| | | String postData = "pid=" + pid; |
| | | |
| | | // 发送 POST 请求 |
| | | try (OutputStream os = connection.getOutputStream()) { |
| | | byte[] input = postData.getBytes("utf-8"); |
| | | os.write(input, 0, input.length); |
| | |
| | | // 读取响应 |
| | | BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
| | | String inputLine; |
| | | StringBuffer response = new StringBuffer(); |
| | | StringBuilder response = new StringBuilder(); |
| | | |
| | | while ((inputLine = in.readLine()) != null) { |
| | | response.append(inputLine); |
| | | } |
| | | in.close(); |
| | | result = response.toString(); |
| | | |
| | | return response.toString(); |
| | | |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | // 返回缓存或错误信息 |
| | | if (lastResult != null) { |
| | | return lastResult; |
| | | } |
| | | return "{\"error\":\"请求失败:" + e.getMessage() + "\"}"; |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | @Override |