Email code makes the code slower in java spring MV

2019-09-05 06:21发布

I have added this is my controller

@RequestMapping(value = "/persons/add", method = RequestMethod.POST)
        public String add(@Valid @ModelAttribute("personAttribute") Person person,
                BindingResult result) {
        logger.debug("Received request to add new person");


        SimpleMailMessage mailMessage = new SimpleMailMessage();

        mailMessage.setTo("someone@abc.com");
        mailMessage.setSubject("This is the test message for testing gmail smtp server using spring mail");
        mailMessage.setFrom("abc@gmail.com");
        mailMessage.setText("This is the test message for testing gmail smtp server using spring mail. \n" +
                "Thanks \n Regards \n Saurabh ");
        mailSender.send(mailMessage);


        if (result.hasErrors())
                return "hibernate/addpage";
        else
        personService.add(person);

                return "hibernate/addedpage";
    }

NOw it takes 5-6 seconds after pressing add button

4条回答
劫难
2楼-- · 2019-09-05 06:42

Like David said, use an async API. I don't recommend creating a new thread. Creating a thread per request here can potentially mean that many many threads get created to service concurrent requests. Better to use a thread pool executor with a limited pool size and enqueue jobs that perform the mail sending. Google java executors and how to use them within spring; there are various implementations. This would mean your requests don't block and they will execute as quickly as if you were not sending mail at all (pretty much).

Alternatively, use a local mail server - sending via a mail server running on localhost is much faster, but I'd recommend the async approach. There are things to consider if going down the async route however, such as how to handle mail send failure. Is it critical that your flow of execution is different in an error condition or can you safely ignore it?

查看更多
等我变得足够好
3楼-- · 2019-09-05 06:49

is this a question?

you are sending the mail synchronously - this might take a few seconds. whats the problem?

i think its also likely that gmail works....

查看更多
We Are One
4楼-- · 2019-09-05 06:54

Better to use Async mail service.

Spring TaskExecutor for Mail

查看更多
在下西门庆
5楼-- · 2019-09-05 07:09

That's probably to be expected. Submitting a mail message to a mail server is not instantaneous.

If that's a problem; use an asynchronous API for sending the message (or start a Thread to do it).

查看更多
登录 后发表回答