springboot integrates multithreading functions

Posted by rubric on Sat, 05 Oct 2019 22:37:52 +0200

Reference articles
https://segmentfault.com/a/1190000015766938
https://blog.csdn.net/qq_34545192/article/details/80484780

Usually we write multi-threads by using new Thread() or creating thread pools, but in Ali's java development specification, we require not to create new threads directly, but through thread pools. Sprboot supports multi-threaded development, so I try to solve the original request of sending mail synchronously temporarily through multi-threads. The problem is too long. Of course, multithreading can not completely solve the problem of asynchrony, but it still needs to decouple functions through message middleware to achieve real asynchrony.

1. Add @ EnableAsync annotation to the startup class of springboot

@SpringBootApplication
@EnableAsync
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

2. Add ThreadConfig configuration class

@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(15);
        executor.setQueueCapacity(25);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

3. Let's write the business implementation of the multithreaded part.

@Component
public class EmailTool {
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendFrom; //Read the parameters in the configuration file

    @Async
    public void sendEmailAsync(EmailEntity emailEntity, CountDownLatch latch) {
        sendEmail(emailEntity);
        latch.countDown();
    }

    public void sendEmail(EmailEntity emailEntity) {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);//Here you can customize the mailing name
            helper.setFrom(sendFrom);
            helper.setTo(emailEntity.getSendTo());
            helper.setSubject(emailEntity.getSubject());
            helper.setText(emailEntity.getMessage(),
                    true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        javaMailSender.send(message);
    }
}

The asynchronous function of sendEmailAsync function can be realized through the above steps, but the problem we should pay attention to when using this method is

@ Invalidity of Async

Asynchronous methods and invocation methods must be written in different classes. If they are written in one class, they are ineffective.

Topics: Java SpringBoot Spring