发送邮件在Java中需要太多时间,我该如何克服



在我的春季启动项目中,我有一个功能,发送电子邮件,电子邮件中,它花费了太多时间来发送交易。

//service layer
    @Transaction
    function inviteUser() {
     // insert in invitation table
     // insert in invitation sub-table
     // sending  mail to user (30 seconds)
    }

在发送邮件中需要大约30秒钟的时间,我该如何克服。还有其他特定方法可以执行这种功能吗?

在弹簧启动中,您可以使用@Async注释,

@Transactional
    public void register() {
   //after success call that method
    emailService.sendWelcomeMail();
    }

    @Service
    @Configuration
    @EnableAsync
    public class EmailService {
        // for sending email
        @Async
        public void sendWelcomeMail(){}
    }

@kayaman和@jerrychin评论说,可能无需发送电子邮件作为数据库交易的一部分:

//服务层

// Inject r/w transaction template.
// No @Transactional annotation
function inviteUser() {
    txTemplate.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus txStatus) {
          // insert in invitation table
          // insert in invitation sub-table
          ...
        }
    });
    // sending  mail to user
}

在应用程序中,我们通常必须从各种来源获取数据,例如第三方网络服务,分布式数据渠道,甚至在我们的应用程序微服务中分布式为累积网络。让我们采用一个方案,您需要从多个来源获取数据并将其组合成单个结果并返回呼叫者。例如。我们有下面呼叫服务的邀请:

服务1 --->从WebServices mywebservice.com获取数据(响应时间10秒,超时15秒(。

服务2 --->从某些第三方API,www.free.com/api/getdata获取数据(响应时间5秒,超时15秒(。

服务3 --->从您自己的微服务/mymicroservice/api/getdata中获取数据(响应时间1秒,超时15秒(,

因此,在同步模式下,即使所有三个服务都正确运行,getMyDataService也将至少10 5 1 = 16秒。假设服务1&amp;2下降。现在,GetMyDataService的响应时间将为15 15 1 = 31秒,以获得响应。(响应仅包括结果fron服务3(

如果未配置超时怎么办???申请将挂断,永远等待响应。

要克服上述情况,Netflix的救援人员" Hystrix"。在此项目中,我们将在下面证明:

GetMyDataService将以15秒的超时为单位。我们将收到最大15秒或更短的最大响应。关于任何服务或超时的失败,我们将有后备,中断线程正在等待服务并返回空白结果。

有关HyStrix检查的详细解释:https://github.com/netflix/hystrix/wiki/how-to-to-use

@Service
public class MailService extends HystrixCommand<Boolean>{
protected MailService(){
    super(HystrixCommandGroupKey.Factory.asKey(MailService.class.getSimpleName()));
}

protected Boolean getFallback(){
    return new Boolean;
}
@Override
protected List<String> run() throws Exception {
     //Send Mail Here
}
}

并使用此

调用它
@Service
public class MyService {
@Autowired
MailService mailService;

public Boolean sendMail() throws InterruptedException, ExecutionException {
    Boolean isMailSend=new Boolean;
     Observable.merge(mailService.observe().subscribeOn(Schedulers.io())).toBlocking().subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean b) {
                     isMailSend = b;
                }
            });
     return isMailSend;
    }
}

最新更新