7

アプリケーションを開発していますが、そのアプリケーションがメールを送信する場合があります。例えば;

ユーザーが電子メールを更新すると、新しい電子メール アドレスを検証するためにアクティベーション メールがユーザーに送信されます。これがコードの一部です。

............
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;

私の問題は、メール送信のために応答時間が長くなることです。ノンブロッキングの方法でメールを送信する方法はありますか? たとえば、メール送信はバックグラウンドで実行され、コードの実行は継続されます

前もって感謝します

4

2 に答える 2

7

別のスレッドで実行するように、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

Spring doc は、セットアップを支援するのに十分なはずです。

于 2013-08-06T18:23:48.847 に答える