如何分离业务逻辑和电子邮件发送功能? [英] How can I separate business logic and email sending functionality?

查看:145
本文介绍了如何分离业务逻辑和电子邮件发送功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的java web应用程序中有一个要求,我需要针对特定​​条件发送电子邮件警报。为此,我使用了javax mail api并发送电子邮件工作正常。但问题是程序执行等待直到执行发送电子邮件的方法。由于在不同的点上发送了数百封电子邮件......这会大大降低性能。

I have a requirement in my java web application where I need to send email alerts for certain conditions. For this I have used javax mail api and sending email works just fine. But the problem is the programs executions waits until the methods for sending the email are executed. As there are hundreds of email to be sent at various points ... this reduces the performance significantly.

我使用spring并且还使用了spring aop。任何人都可以建议我如何分离我的业务逻辑和发送电子邮件功能。它应该像 -

I am using spring and have also used spring aop. Can anyone suggest me how can I separate my business logic and sending email functionality. It should be like -

发送电子邮件是我的建议,在调用xyz方法时执行 - 因此主要执行不应该等待建议完成其执行而应该返回返回并执行进一步的业务逻辑,从而单独执行电子邮件发送。

Sending emails is my advice which gets executed when xyz method is called - So main execution should not wait for advice to finish its execution rather it should return back and execute further business logic thus email sending executed separately.

这里创建新线程似乎是明显的选择。但我认为可能有更好的方法,是吗?谢谢。

Here creating new threads seems obvious choice. But I think there could be some better way, is there? Thanks.

推荐答案

你所描述的是异步执行和自然的异步执行方式是Java是使用线程。

What you describe is asynchronous execution and natural way to do async execution is Java is to use threads.

你可以引入一些执行者,例如 Executors.newFixedThreadPool(),并使用它将邮件任务卸载到单独的线程中。

You can introduce some Executor, e.g., Executors.newFixedThreadPool(), and use it to offload mailing task into separate threads.

Aspect本身是一个不合适的地方,因为这会将状态引入方面,例如,你可能想要使用返回的 Future 检查邮件任务是否成功:

Aspect itself is a unsuitable place for this, since this would introduce state into aspect, for example, you may want to check if mail task was successful by using returned Future:

class Mailer {
    private final ExecutorService executor = Executors.newFixedThreadPool(maxMailingThreads);
    //...
        public void doMail(MailTask anEmail) {
            Future<MailTaskResult> future = executor.submit(new MailTask(anEmail));
            future.get().isSuccessful(); // handle success or failure somehow
        }

更好地将此逻辑移动到单独的类中并调用从某种方面来看它。

Better move this logic into separate class and call it from aspect somehow.

这篇关于如何分离业务逻辑和电子邮件发送功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆