我有一个与JavaMailSender
有关的问题,它会发送两到三条重复的信息。
在控制器中:
while(size > 0) //# of emails I want to send, for example 5
{
Item item= itemRepository.findFirstBySentFalseAndValidTrue(); //getting only emails that are not sent!
item.getData(); // API call that adds some info to the item, takes between 5-15 seconds per item
if(item.isValid())
{
item.setHeaderName(dataService.setHeader(item.getStore(), LocaleContextHolder.getLocale()));
item.setAddress(dataService.getAddress(item.getStore(), LocaleContextHolder.getLocale()) + item.getId());
String email = dataService.getEmail(item.getStore());
String footer = dataService.getFooter(item.getStore(), LocaleContextHolder.getLocale());
if(!item.isSent()) //I check if sent here but still get double messages!
{
if(mailSenderService.sendEmail(item, "emails/templates/item", email, footer))
{
item.setSent(true);
}
}
itemRepository.save(item);
size--;
}
}
在我的电子邮件发送服务类中:
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true, "UTF-8");
Context ctx = new Context(LocaleContextHolder.getLocale());
message.setFrom(email);
message.setTo("test@gmail.com");
ResourceBundle labels = ResourceBundle.getBundle("messages", LocaleContextHolder.getLocale());
mimeMessage.setHeader("Content-Type", encodingOptions);
mimeMessage.setSubject(labels.getString("email.itme.title"), "UTF-8");
ctx.setVariable("data", item);
ctx.setVariable("footer", footer);
try{
String processedTemplate = templateEngine.process(template, ctx);
mimeMessage.setContent(processedTemplate, encodingOptions);
this.mailSender.send(mimeMessage);
} catch(Exception e){
e.printStackTrace();
}
return true;
}
我猜这可能是我的邮件发送类的问题,但也有可能是API调用太慢,导致方法执行时间过长,从而发送了重复的消息?有时候,当我只发送几封邮件(比如3封)时,一切都很好,不会发送重复的邮件。但是,当我想要发送20或30封邮件时,所有的东西都需要约15分钟,然后我就会收到重复的邮件(我不能控制API的响应时间,有时它会快一些,有时则会非常缓慢)。我能否以某种方式进行调试,并查看哪个方法在何时被调用,为什么会出现这些重复数据呢?
编辑: 这是我的itemRepository实现:
@Repository
@Qualifier(value = "itemRepository")
@Transactional
public interface itemRepository extends CrudRepository<Item, Long> {
public Item save(Item item);
public Item findFirstBySentFalseAndValidTrue();
}
itemRepository.save(item)
是如何实现的?也许是在save
操作未持久化之前,findFirstBySentFalseAndValidTrue()
获取了过期数据,导致了某种竞态条件? - Dirk Lachowski