0

遵循我使用 Spring 3 TaskExecutor 为异步邮件发送所做的代码。代码工作正常,我只想知道是否有任何邮件因任何原因未能发送,然后必须再次将其添加到队列中并且必须重试发送。

我已经用 Google 搜索过,但没有获得有关重试政策的信息。

帮助将不胜感激!

@Service
public class AsyncMailSender implements MailSender {

    /* Logger for Search-Controller Class */
    public static final Logger LOGGER = Logger.getLogger(AsyncMailSender.class);

    @Autowired
    private MailSender mailSender;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private VelocityEngine velocityEngine;

    public void send(SimpleMailMessage simpleMessage) throws MailException {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("user", "Manoj");
        simpleMessage.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "templates/email.vm", modelMap));
        taskExecutor.execute(new AsyncMailTask(simpleMessage));
    }

    public void send(SimpleMailMessage[] simpleMessages) throws MailException {
        for (SimpleMailMessage message : simpleMessages) {
            send(message);
        }
    }

    private class AsyncMailTask implements Runnable {

        private SimpleMailMessage message;

        private AsyncMailTask(SimpleMailMessage message) {
            this.message = message;
        }

        public void run() {
            LOGGER.info("Sending Emails" + message.getSubject());
            mailSender.send(message);
        }
    }
}
4

3 回答 3

2

AFAIK,目前无法使用 Spring 3 TaskExecutor 配置重试,有一个与之相关的SPR。话虽如此,我认为如果抛出任何异常,Spring 会自动重试该方法。如果异常不断重复,这对您来说可能是个问题(在资源消耗方面)。

于 2013-01-01T14:41:13.600 回答
2

这可能并不理想,但您可以在任务中使用Spring-Retry,如下所示:

@Service
public class AsyncMailSender implements MailSender {

    @Autowired
    RetryTemplate retryTemplate;

    private class AsyncMailTask implements Runnable {

        private SimpleMailMessage message;

        private AsyncMailTask(SimpleMailMessage message) {
            this.message = message;
        }

        public void run() {
            retryTemplate.execute(new RetryCallback<Void, PersistenceException>() {

                    LOGGER.info("Sending Emails" + message.getSubject());
                    mailSender.send(message);

                    return null;
                }
            });

        }
    }

您可以像这样配置 RetryTemplate:

@Configuration
public class RetryConfiguration {

    @Bean 
    RetryTemplate retryTemplate() {

        RetryTemplate template = new RetryTemplate();

        TimeoutRetryPolicy policy = new TimeoutRetryPolicy();
        policy.setTimeout(30000L);

        template.setRetryPolicy(policy);

        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        template.setBackOffPolicy(backOffPolicy);

        return template;
    }
}

您可能还会发现Spring-Batch很有用。

于 2014-10-30T21:51:00.600 回答
0

春天不适合你

您必须自己进行异常处理和排队。它TaskExecutor本身具有重试能力,因为它只是在下一个配置的时间间隔运行您的任务,无论如何。

于 2013-01-01T20:03:00.750 回答