Use the thread pool to send mail instances in web projects

Source: Internet
Author: User
In a common web application, sending an email can only be considered as a small task. Using JMS to send an email is a bit tricky, if you can create a thread pool to manage these small threads and reuse them, it is a simple and effective solution. We can use executors in the concurrent package to create a thread pool, executors is a factory and a tool class. I have simply translated its API introduction (if the translation is incorrect, please do not mean the bricks in your hands)
/*** For the thread pool class managed by spring, the returned executorservice is for us to execute the thread * if it is not handed over to spring management, you can use the singleton mode to implement the same function, but the poolsize * requires hardcode * @ author Zhang Ronghua (ahuaxuan) * @ version $ ID $ */public class easymailexecutorpool implements initializingbean {// thread pool size, private int poolsize configured in the spring configuration file; private executorservice service; Public executorservice getservice () {return service;} public int getpoolsize () {return poolsize;} public void setpoolsize (INT poolsize) {This. poolsize = poolsize;}/*** initialize the thread pool size after Bean Initialization is successful */Public void afterpropertiesset () throws exception {service = executors. newfixedthreadpool (poolsize );}}

In this way, the thread pool size is initialized, and the next step is how to use the threads in the thread pool. Let's look at how mailservice uses the threads in the thread pool, I have explained the code in this class in detail.

Code
/*** Refers to the service used to send mail. One internal class is specifically used by the thread * @ author Zhang Ronghua (ahuaxuan) * @ since 2007-7-11 * @ version $ ID $ */public class easymailservieimpl implements easymailservice {Private Static transient log logger = logfactory. getlog (easymailservieimpl. class); // inject mailsender private javamailsender; // inject the thread pool private easymailexecutorpool; // set the sender private string from; Public Vo Id seteasymailexecutorpool (easymailexecutorpool) {This. easymailexecutorpool = easymailexecutorpool;} public void setjavamailsender (javamailsender) {This. javamailsender = javamailsender;} public void setfrom (string from) {This. from = from;}/*** Simple Mail sending interface, you can add * @ Param to * @ Param subject * @ Param text */Public void sendmessage (emailentity E Mail) {If (null = Email) {If (logger. isdebugenabled () {logger. debug ("something you need to tell here");} return;} simplemailmessage = new simplemailmessage (); simplemailmessage. setto (email. getto (); simplemailmessage. setsubject (email. getsubject (); simplemailmessage. settext (email. gettext (); simplemailmessage. setfrom (from); easymailexecutorpool.getservice(.exe cute (New Mail Runner (simplemailmessage);}/*** interface for sending emails in complicated formats. You can add attachments, images, and so on. However, you need to modify this method, * If you have examples of how to add attachments and images on the Forum, You need to search for them. * In fact, the text parameter here is preferably from the template to generate an HTML page using the template, and send it to javamail, * How to use a template to generate HTML see {@ link http://www.iteye.com/topic/71430} ** @ Param to * @ Param subject * @ Param text * @ throws messagingexception */Public void sendmimemessage (emailentity email) throws messagingexception {If (null = Email) {If (logger. I Sdebugenabled () {logger. debug ("something you need to tell here");} return;} mimemessage message = javamailsender. createmimemessage (); mimemessagehelper helper = new mimemessagehelper (Message); helper. setto (email. getto (); helper. setfrom (from); helper. setsubject (email. getsubject (); this. addattachmentorimg (helper, email. getattachment (), true); this. addattachmentorimg (helper, email. getimg (), FAL Se); // The text here is in HTML format. You can use the template engine to generate an HTML template. velocity or freemarker can both be helper. settext (email. gettext (), true); easymailexecutorpool.getservice(.exe cute (New mailrunner (Message ));} /*** add an attachment or image * @ Param helper * @ Param map * @ Param isattachment * @ throws messagingexception */private void addattachmentorimg (mimemessagehelper helper, map, Boolean isattachment) throws messagingexception {for (it Erator it = map. entryset (). iterator (); it. hasnext ();) {map. entry entry = (map. entry) it. next (); string key = (string) entry. getkey (); string value = (string) entry. getvalue (); If (stringutils. isnotblank (key) & stringutils. isnotblank (value) {filesystemresource file = new filesystemresource (new file (value); If (! File. exists () continue; If (isattachment) {helper. addattachment (Key, file);} else {helper. addinline (Key, file) ;}}}/*** is the runnable used to send emails. This class is an internal class. The internal class is used, instead of using nested classes (static internal classes), * because internal classes can get the javamailsender of the Service * each time an email is sent, a thread is retrieved from the thread pool, then execute the mail operation * @ author ahuaxuan */private class mailrunner implements runnable {simplemailmessage; mimemessage;/*** to construct a simple text email * @ Param simplemailmessage */Public mailrunner (simplemailmessage) {If (mimemessage = NULL) {This. simplemailmessage = simplemailmessage;}/*** to construct a complex email. You can add nearby emails, images, and so on. * @ Param mimemessage */Public mailrunner (mimemessage) {If (simplemailmessage = NULL) {This. mimemessage = mimemessage;}/*** this method will be executed in the thread pool */Public void run () {try {If (simplemailmessage! = NULL) {javamailsender. Send (this. simplemailmessage);} else if (mimemessage! = NULL) {javamailsender. send (this. mimemessage) ;}} catch (exception e) {If (logger. isdebugenabled () {logger. debug ("logger something here", e );}}}}}

The emailentity in mailservice is the abstraction of mail (I only use the blood loss model. In fact, we can also let this emailentity implement the runnable interface, so that the internal classes in the service can be removed, at the same time, most of the Code in the service will be moved to emailentity and its parent class. What do you prefer to do ?), The Code is as follows:

/**
* This class is an abstraction of the mail. What attributes does the mail have? Obviously, this class is just an example,
* In this example, the required attachments or images are sent by mimemessage (if any)
* You need to use your own extensions.
*
* @ Author Zhang Ronghua (ahuaxuan)
* @ Version $ ID $
*/
Public class emailentity {

String;

String subject;

String text;

// Email attachment
Map

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.