2013-08-06 41 views
4

我正在開發一個應用程序,並且該應用程序在某些情況下發送郵件。例如;Spring mvc發送郵件爲非阻塞

當用戶更新他的電子郵件時,發送給用戶的激活郵件是爲了驗證新的電子郵件地址。這是一段代碼;

............ 
if (!user.getEmail().equals(email)) { 
      user.setEmailTemp(email); 
      Map map = new HashMap(); 
      map.put("name", user.getName() + " " + user.getSurname()); 
      map.put("url", "http://activationLink"); 
      mailService.sendMail(map, "email-activation"); 
     } 
return view; 

我的問題是響應時間變長,因爲電子郵件發送。有沒有辦法像非阻塞方式發送電子郵件?例如,郵件提前

+2

與['@Async做在一個單獨的線程'](http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html) –

回答

4

您可以設置使用Spring的異步方法在一個單獨的線程運行在發送背景和代碼運行的執行繼續

感謝。

@Service 
public class EmailAsyncService { 
    ... 
    @Autowired 
    private MailService mailService; 

    @Async 
    public void sendEmail(User user, String email) { 
     if (!user.getEmail().equals(email)) { 
      user.setEmailTemp(email); 
      Map map = new HashMap(); 
      map.put("name", user.getName() + " " + user.getSurname()); 
      map.put("url", "http://activationLink"); 
      mailService.sendMail(map, "email-activation"); 
     } 
    } 
} 

我在你的模型上做了一些假設,但假設你可以傳遞方法發送郵件所需的所有參數。如果你設置正確,這個bean將被創建爲一個代理,並且調用@Async帶註釋的方法將在不同的線程中執行它。

@Autowired 
private EmailAsyncService asyncService; 

... // ex: in controller 
asyncService.sendEmail(user, email); // the code in this method will be executed in a separate thread (you're calling it on a proxy) 
return view; // returns right away 

The Spring doc should be enough to help you set it up.

+0

感謝您的幫助! –

-1

同上。

但要記住,使異步任務在Spring配置文件(例如:applicationContext.xml中):

<!-- Enable asynchronous task --> 
<task:executor id="commonExecutor" pool-size="10" /> 
<task:annotation-driven executor="commonExecutor"/> 

或配置類:

@Configuration 
@EnableAsync 
public class AppConfig { 
}