2017-02-17 38 views
1

我正在使用Spring應用程序,並且我們有一個基於REST API的SOA體系結構。我有一個API,例如創建用戶(http://myapp/api/createUser如何實現異步行爲以響應在Java中的響應返回時發送電子郵件

所以現在當用戶創建時,我們需要發送一封電子郵件給用戶。我沒有實現它,但它等待電子郵件方法發​​送電子郵件並返回成功/失敗,這會消耗時間。

請問如何通過在線程中啓動電子郵件部分並在後臺運行並將郵件發送給用戶,從API立即返回成功響應。或者如果失敗,則登錄數據庫。

請爲我推薦API或框架,我不想實現Messaging Queue,比如Rabbit MQ或Active Queue。 請通過產生線程來共享那些不會在實時生產服務器上造成問題的實現。

回答

2

在您的電子郵件發送方法中使用@Async。

編號:http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html

例子:

@Async 
public void sendNotificaitoin(User user) throws MailException {  
    javaMailSender.send(mail); 
} 

爲了使@Async工作,在配置中使用@EnableAsync。

@SpringBootApplication 
@EnableAsync 
public class SendingEmailAsyncApplication {  
    public static void main(String[] args) { 
     SpringApplication.run(SendingEmailAsyncApplication.class, args); 
    } 
} 

使用它象下面這樣:

 @RequestMapping("/signup-success") 
     public String signupSuccess(){ 

      // create user 
      User user = new User(); 
      user.setFirstName("Dan"); 
      user.setLastName("Vega"); 
      user.setEmailAddress("[email protected]"); 

      // send a notification 
      try { 
       notificationService.sendNotificaitoin(user); 
      }catch(Exception e){ 
       // catch error 
       logger.info("Error Sending Email: " + e.getMessage()); 
      } 

      return "Thank you for registering with us."; 
     } 
+0

我想回應將不會被接受,直到notificationService.sendNotificaitoin(用戶);完成發送。 確認嗎?併發送文件,如果這是寫在某個地方。 –

+0

不行,請檢查通過運行。 sendNotificaitoin()被標記爲async()。 – mhshimul

+0

我試圖調試仍然獲得的同步行爲。我已經把@Async放到了我的方法中,因爲我沒有使用spring boot,所以在app-config.xml中添加了。不知道在哪裏添加EnableAsync ?.你能幫忙嗎? –