2012-09-18 19 views
0

使用下面顯示的編碼,我設法從服務器上的sql數據庫使用php來檢索數據。 我需要定期檢查數據庫,看看是否有新的數據添加,如果有的話,我需要將它們檢索到我的Java應用程序。 我使用netbeans IDE 我該怎麼做?每當mysql數據庫發生變化時,獲取一個http請求到一個Java應用程序

try { 
    URL url = new URL("http://taxi.com/login.php?param=10"); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Accept", "application/json"); 

    if (conn.getResponseCode() != 200) { 
     throw new RuntimeException("Failed : HTTP error code : " 
       + conn.getResponseCode()); 
    } 

    BufferedReader br = new BufferedReader(new InputStreamReader(
     (conn.getInputStream()))); 

    String output; 
    System.out.println("Output from Server .... \n"); 
    while ((output = br.readLine()) != null) { 
     System.out.println(output); 
    } 

    conn.disconnect(); 

    } catch (MalformedURLException e) { 

    e.printStackTrace(); 

    } catch (IOException e) { 

    e.printStackTrace(); 

    } 

} 
+0

看起來像MS推出的[SQL_Server_Notification_Services(HTTP:// EN。 wikipedia.org/wiki/SQL_Server_Notification_Services),但總的想法是數據庫將任何變化(你感興趣的)發信號給一個[JMS](htt p://www.oracle.com/technetwork/articles/java/introjms-1577110.html)隊列或其他東西,讓您的應用程序訂閱該JMS主題並接收通知。 – asgs

+0

感謝您的信息!你有任何具體的例子或編碼,我可以參考?因爲我是JMS新手,它的工作原理! :) – senrulz

回答

0

在這個解決方案,我認爲至少使用Java 5的
假設您想每5分鐘檢查一次新數據並在25分鐘後終止。
你這樣做:

PHPDataChecker.java

public class PHPDataChecker implements Runnable { 
    public void run() { 
     // Paste here all the code in your question 
    } 
} 

Main.java

public class Main { 
    private static boolean canStop=false; 

    private static void stopPHPDataChecker() { 
     canStop=true; 
    } 

    public static void main(String[] args) { 
     // Setup a task for checking data and then schedule it 
     PHPDataChecker pdc = new PHPDataChecker(); 
     ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 
     final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(pdc, 0L, 5L, TimeUnit.MINUTES);// Start pooling 

     // Setup a new task to kill the polling after 25 minutes 
     scheduler.schedule(new Runnable() { 

      public void run() { 
       System.out.println(">> TRY TO STOP!!!"); 
       pdcHandle.cancel(true); 
       Main.stopPHPDataChecker(); 
       System.out.println("DONE"); 
      } 

     }, 25L, TimeUnit.MINUTES); 

     // Actively wait stop condition (canStop) 
     do { 
      if (canStop) { 
       scheduler.shutdown(); 
      } 
     } while (!canStop); 

     System.out.println("END"); 
    } 
} 
+0

謝謝你的回答!我試過這個,但我得到了第4行和第5行的錯誤,說非法開始表達 – senrulz

+0

,當我刪除'私人最終'的錯誤消失了!刪除它們可以嗎? – senrulz

+0

好吧,它似乎工作正常! :) 謝謝您的回答! – senrulz

相關問題