2016-09-24 16 views
0

我有一個代理微服務從API讀取並返回一些過濾的輸出。我正在使用HttpsURLConnection(使用URLConnection中的方法)。如何使用URLConnection每小時刷新緩存?

String httpsURL = "https://myrestserver/path"+ id ; 
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy", 8080)); 
URL myurl = new URL(httpsURL); 
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection(proxy); 
con.setRequestMethod("GET"); 
con.setRequestProperty("Content-Type","application/json"); 
con.setRequestProperty("Authorization", authString); 
con.setDoInput(true); 
DataInputStream input = new DataInputStream(con.getInputStream()); 
result = new Scanner(input).useDelimiter("\\Z").next(); 

我想使用緩存來減少我的流量和延遲,但我想每小時更新一次。

我的問題是:如何使用URLConnection每小時刷新一次緩存?

假設 - Java 7中

+0

以上,在文檔閱讀,如果您再次打開連接並執行的getInputStream (),它會導致數據刷新。這與java.util.Timer相關聯可能是你需要的。我想念一些明顯的東西嗎? –

+0

我不需要將定時器執行與客戶端調用微服務的時間結合起來嗎? – hawkeye

回答

0

從我個人理解,你需要在固定的時間間隔來調用重複客戶。這是一種做法(Java7)。不確定這是否符合您的需求。這裏每2秒在一個虛擬URL上進行服務調用。由於一次又一次所謂的任務,數據將被刷新(數據輸入流將根據從服務器返回的數據)

import java.io.DataInputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.Timer; 
import java.util.TimerTask; 

public class CallAPIProxy { 
    Timer timer; 

    public CallAPIProxy(int seconds) { 
     timer = new Timer(); 
     // timer.schedule(new APICallerTask(), seconds * 1000); 
     timer.scheduleAtFixedRate(new APICallerTask(), 2000, 2000); 

    } 

    class APICallerTask extends TimerTask { 
     public void run() { 
      String httpsURL = "http://jsonplaceholder.typicode.com/posts/1"; 
      // String httpsURL = "https://myrestserver/path" + id; 
      // Proxy proxy = new Proxy(Proxy.Type.HTTP, new 
      // InetSocketAddress("myproxy", 8080)); 
      URL myurl; 
      try { 
       myurl = new URL(httpsURL); 
       System.setProperty("http.agent", "Chrome"); 

       // HttpsURLConnection con = (HttpsURLConnection) 
       // myurl.openConnection(proxy); 
       HttpURLConnection con = (HttpURLConnection) myurl.openConnection(); 
       con.setRequestMethod("GET"); 
       // con.setRequestProperty("Content-Type", "application/json"); 
       // con.setRequestProperty("Authorization", authString); 
       con.setDoInput(true); 
       DataInputStream input = new DataInputStream(con.getInputStream()); 
       // String result = new 
       // Scanner(input).useDelimiter("\\Z").next(); 
       // Scanner result = new Scanner(input); 
       StringBuffer inputLine = new StringBuffer(); 
       String tmp; 
       while ((tmp = input.readLine()) != null) { 
        inputLine.append(tmp); 
        System.out.println(tmp); 
       } 
       input.close(); 
       System.out.println("Result " + inputLine); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static void main(String args[]) { 
     System.out.println("About to call the API task."); 
     new CallAPIProxy(2); 
     System.out.println("Task scheduled."); 
    }