2014-12-06 66 views
0

我正在使用Spring構建的WebService項目。所有配置都使用Annotation完成。有一種方法發送推送通知。由於有很多通知要發送,導致響應延遲。所以,我將@Async註釋應用於我的「sendPushnotification」方法。但是,反應仍然沒有改善。我已經通過一些博客和計算器找到解決方案。但是,沒有成功。我已將以下注釋應用於我的Service類。@Async不能在REST類中工作

@Component 
@Configuration 
@EnableAspectJAutoProxy 
@EnableAsync 

從中調用異步的方法。

@POST 
@Path("/sampleService") 
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
public Response sampleService(@FormParam ...) { 
    ... 
    List<User> commentors = <other method to fetch commentors>; 
    sendPushnotification(commentors); 
    ... 
} 

我的異步方法。

@Async 
private void sendPushnotification(List<User> commentors) { 
    if (commentors != null) { 
     for (User user : commentors) { 
      try { 
       int numNewComments = ps.getCommentsUnseenByUser(user); 

       sendMessage("ios", user, "2", "" + numNewComments, "true"); 
      } catch (Exception e) { 
       log.error(e.getMessage(), e); 
      } 
     } 
    } 
} 

有什麼我失蹤?

+0

你是否註冊了一個具有適當數量的線程的執行器? – 2014-12-06 05:01:01

+0

您是否已經正確整合了Jersey(或您使用的任何JAX RS實現)與Spring? – 2014-12-06 05:01:38

+0

是的。它配置正確。該應用程序工作得很好。所有請求和回覆都很好。 – 2014-12-06 05:05:18

回答

1

你調用上this

sendPushnotification(commentors); 
// equivalent to 
this.sendPushnotification(commentors); 

是行不通的方法。 Spring通過代理你的bean來提供功能。它給你一個代理bean,它具有對真實對象的引用。因此,主叫方看到並調用

proxy.someEnhancedMethod() 

但發生的事情是

proxy.someEnhancedMethod() -> some enhanced logic -> target.someEnhancedMethod() 

但在你sampleService服務方法,你不必代理的引用,具有對目標的參考。基本上,你一無所獲。我建議將@Async邏輯移至不同的類型,並將該類型的bean聲明並注入資源。

Spring在文檔here中解釋了上述所有內容。

+0

我在查看鏈接。 – 2014-12-06 06:59:11

相關問題