Вопрос

I want to send an email activation link to a registered user. I already set up my Sendmail.class which work` perfectly.

Here is the scenario:

  1. the user request for registration by providing information via a restful client
  2. the restful endpoint gets the request to do some business operation and sends a computed code to the email of the registered user and returns a response saying 'successfully registered'

The problem is that I don't want to wait for the Sendmail.class to finish the sending process (it may fail) to return the 'successfully registered message

How can I handle this process using Java EE?

Это было полезно?

Решение

Put the code that sends the email in an @Asynchronous method.

Example:

@Stateless
public class EmailSender {

    @Asynchronous
    public void sendMail(...) {
        // send mail here
    }

}

From the place where you do your business logic:

@Inject
private EmailSender emailSender;

public Foo myBusiness() {
    // Compute stuff

    emailSender.sendMail(stuff); // returns immediately 

    // do other stuff if needed
}

See the Oracle tutorial for some extra info.

Другие советы

Put your e-mail sending code in a thread. Even you can easily use SwingWorker:

SwingWorker worker = new SwingWorker() {
        @Override
        protected void done() {
        }

        @Override
        protected Object doInBackground() throws Exception {
           // Send your e-mail here.
        }
    };
    worker.execute();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top