spring boot sends mail asynchronously

demand

I use my own mobile phone to verify my login, and then I want to send the verification code to the bound email when the mobile phone verification code fails to be sent. (it mainly costs money to send the mobile phone verification code, so I don't want to package the package for my study and test project. Then I want to be familiar with the operations of email verification. I'm sure I won't play this way in actual development. Then, if I send the verification code directly to the mobile phone - > failure - > email verification. This is very time-consuming. It takes about 1000+ms, so I think how to optimize this operation.). Sending e-mail is a time-consuming operation, which may take tens of seconds. However, the interface is completed in an instant. In order not to affect the performance of the interface, it is necessary to carry out asynchronous operation on the operation of sending e-mail.

process

  • First, we need to introduce the test module of sending mail
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
public interface EmailServer {

    void  sendemail(String  subject,String from ,String touserEmail,String text);
}
  • Implement this interface
@Component
@Service
public class EmailServerImpl implements EmailServer {
    @Autowired
    private JavaMailSender javaMailSender;
    @Async("taskExecutor")
    @Override
    public void sendemail(String subject, String from, String touserEmail, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setFrom(from);
        message.setTo(touserEmail);
        message.setSentDate(new Date());
        message.setText(text);
        javaMailSender.send(message);
    }
}
  • Injection controller
  @Autowired
    private EmailServer emailServerl;
  • springboot starts asynchronously
@EnableAsync//Add comments to startup items
  • Configuration of asynchronous tasks
@Configuration
public class TaskPoolConfig {
    @Bean("taskExecutor")
    public Executor taskExecutor () {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // Number of core threads 10: the number of threads initialized when the thread pool is created
        executor.setCorePoolSize(10);
        // Maximum number of threads 20:
        executor.setMaxPoolSize(15);
        // Buffer queue 200:
        executor.setQueueCapacity(200);
        // Allow thread idle time of 60 seconds:
        executor.setKeepAliveSeconds(60);
        // Prefix of thread pool name:
        executor.setThreadNamePrefix("taskExecutor-");
        /*
        The processing policy of the thread pool for rejecting tasks: the CallerRunsPolicy policy is adopted here,
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // When setting the thread pool to close, wait until all tasks are completed before continuing to destroy other beans
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // Set the waiting time of tasks in the thread pool. If they are not destroyed after this time, they will be forcibly destroyed,
        executor.setAwaitTerminationSeconds(600);
        return executor;
    }
}

Then you can send mail asynchronously. The efficiency is about 200+ms. Most of the time is the stage of SMS verification code - > fail or not. In fact, asynchronous email has reached about 8-10ms. For me, that should be it. This is mainly because I need to judge the returned information after sending SMS, and then decide whether to send SMS through email. If it is a serious project, the two-way approach will certainly not be designed in this way. It should belong to two different verification chains. Then the two verification chains can send the verification code in an asynchronous manner independently. In other words, when the user submits a request at the front end, it will immediately receive the verification code and send the successful information. Then the background is sending the verification code asynchronously at this time. I use thread pool to process asynchronously. In fact, messages can also be processed through middleware.

Tags: Spring Boot

Posted by cdjsjoe on Wed, 18 May 2022 10:47:49 +0300