1

我目前正在使用Java開發Restfull體系結構下的應用程序。在我的網絡休息服務,另一個web服務soap和android客戶端之間的交互過程中,我遇到了一個非常大的問題。java中的異步處理技​​術和設計

經過多次測試後,我意識到客戶端有時會在處理過程中返回操作失敗,並且上述兩種服務之間的服務消耗相同,原因很簡單,因爲這些大小寫呼叫都是阻塞的。

爲了解決這個問題,我會這樣做: 當客戶端向服務器發送操作時,服務器立即響應請求被採取。然後,客戶將不得不每次測試其操作的狀態,直到它很好地通知用戶。

現在我擔心的是我只會爲此創建一個線程;但我找不到一個好的設計和技術......先謝謝你的幫助。

+0

你可以讓你的客戶端異步和解決您最實際的問題。但是如果你堅持有雙向服務(例如,請求排隊和/或響應需要很長時間),請在客戶端發佈通知服務以接收服務器操作的結果,並實現關聯的方式對之前發送的請求的響應通知。在這種情況下,兩端在技術上都是客戶端和服務器,但我們始終向發起者調用客戶端。 – acelent

+0

感謝您關注我的問題。就你提出的兩個解決方案而言,我已經實施了第一個解決方案。第二個將是該項目的另一個迭代的主題,這個迭代將構成研究和開發 – FiokoSoft

回答

0

您應該監聽來自客戶端的調用(在服務器端點之一上)輪詢狀態,並讓消費者線程實現getStatus方法,同時更新run方法中的狀態。關於消費者線程,粗的實施將看起來像:

public class ConsumerThread implements Runnable{ 
    private int status = 0; 
    private Random rand = new Random(); 
    private final CountDownLatch startSignal; 

    public ConsumerThread(CountDownLatch latch){ 
     this.startSignal = latch; 
    } 

    public int getStatus() { 
     return status; 
    } 

    private void setStatus(int status) { 
     this.status = status; 
    } 

    public void run() { 
     try { 
      this.startSignal.await(); 
      while (true){ 
       this.setStatus(rand.nextInt(10)); 
      } 
     } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
     }  
    } 
} 

然後嘗試一個簡單的main方法(我實現了一個CountDownLatch有我的所有線程開始在同一時間,它不是強制性的):

public class ThreadMain{ 
    private static List<ConsumerThread> consumers = new ArrayList<ConsumerThread>(); 

    public static void main(String[] args) { 
     int NUM_THREAD = 15; 
     ExecutorService executor = Executors.newFixedThreadPool(NUM_THREAD); 

     CountDownLatch latch = new CountDownLatch(NUM_THREAD); 
     ConsumerThread buffer = new ConsumerThread(latch); 
     for (int i = 0; i < NUM_THREAD; i++){ 
      consumers.add(buffer); 
      executor.execute(buffer); 
      latch.countDown(); 
      buffer = new ConsumerThread(latch); 
     } 

     for (int i = 0; i < 100; i++){ 
      System.out.println("Status for Thread 0: " + getStatusId(0)); 
      System.out.println("Status for Thread 14: " + getStatusId(14)); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static int getStatusId(int index){ 
     return consumers.get(index).getStatus(); 
    } 
} 

輸出示例:

Status for Thread 0: 5 
Status for Thread 14: 0 
Status for Thread 0: 7 
Status for Thread 14: 2 
Status for Thread 0: 7 
Status for Thread 14: 4 
Status for Thread 0: 6 
Status for Thread 14: 3 
+0

感謝你assettouf,我解決了我的問題 – FiokoSoft

+0

@FiokoSoft沒問題,請記住標記答案爲答案標記問題解決了。 – Adonis