Spring Boot Rest Rest API 上的异步 - 注释应该仅在服务或控制器上

use*_*453 5 java spring-boot spring-async

我必须在 Spring Boot 中实现具有异步功能的方法:

我对注释异步的位置有点困惑,基本上我的休息控制器如下:

@RestController
@RequestMapping("/email")
public class EmailController {

    public @ResponseBody ResponseEntity<String> sendMailCon(@RequestBody EmailRequestDto emailRequestDto) {
        LOG.debug("calling method sendMail from controller ");
        //do complex stuff 
        sendMailService.sendEmail(emailRequestDto);
        return new ResponseEntity<>("Mail has been sent successfully", HttpStatus.OK);
    }
Run Code Online (Sandbox Code Playgroud)

服务等级如下:

@Component
public class SendMailServiceImpl implements SendMailService {

    private static final Logger LOG = LoggerFactory.getLogger(SendMailServiceImpl.class);

    @Autowired
    private JavaMailSender javaMailSender;
@Override
    @Async("threadPoolExecutor")
    public void sendEmail(EmailRequestDto emailRequestDto) {

        LOG.debug("calling method sendMail do complex stuff");
...
}
Run Code Online (Sandbox Code Playgroud)

我的异步 bean 配置如下:

@EnableAsync
@Configuration
public class AsyncConfig {

    @Bean(name = "threadPoolExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(25);
        executor.setQueueCapacity(100);
        executor.initialize();
        return executor;
    } 
Run Code Online (Sandbox Code Playgroud)

我的问题是 SendMailServiceImpl 上的注释 @Async 是正确的,还是我需要将其添加到控制器的 sendMailCon 方法上?

Ana*_*han 5

基本上@Async将使方法在单独的线程中执行,即调用者不会等待被调用方法的完成。对服务器的每个请求都已由单独的线程提供服务,因此您无需@Async在控制器方法上提供。

您可以将其保留在服务层或更好的另一层中,您实际上需要异步执行该方法。在您的情况下,您实际上可以将该方法保留为异步,其中您使用休息模板来触发邮件。如果您不这样做没有另一个类可以将服务层方法保持为异步。