1

我想写异步方法。

@Component
public class TaskImpl implements Task{

    @Async(value="myExecutor")
    public void async(int n) throws InterruptedException{
        log.info("Executing task"+n);
        Thread.sleep(1000);
        log.info("Finished executing task" +n);

    }

}

很好!我有这样的配置:

<task:annotation-driven executor="myExecutor" />    
<task:executor id="myExecutor" pool-size="3" />

那很好!我也有写测试课!

    @Autowired
    private Task task;

    @Test
    public void mailSendTest() throws InterruptedException{
        for (int i = 0; i <5; i++) {
            task.async(i);
        }
        Thread.sleep(3000)

    }

我已经测试过并且异步工作得很好!任务是并行的!

问题1. 但是当测试用例的主线程销毁时,执行线程不起作用。换句话说,如果我不在测试用例中编写 Thread.sleep() , Executor 会立即击落。我该如何解决?

2015-03-12 17:02:26.706  INFO ThreadPoolTaskExecutor: Shutting down ExecutorService

我不想写 JOIN 或 Sleep。

问题 2. 我需要 async() 方法来调用邮件发件人类。换句话说,我已经编写了这个组件。

@Component
public class MailMail {

    private MailSender mailSender;

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Async
    public void sendMail(String from, String to, String subject, String msg)   {

        ....
    }


    }
}

现在我对如何解决以下问题感兴趣。可能是通信,网络问题,我无法发送电子邮件。现在会发生什么?如何捕获异常并再次发送?

4

1 回答 1

0

对于测试用例,您可以Mockito.spy使用TaskImplCountDownLetchdoAnswer()测试方法结束时等待letch。

对于那些异步任务的错误处理,您可以使用ErrorHandlingTaskExecutorSpring Integration 并为其提供ErrorHandler

于 2015-03-12T13:30:22.747 回答