JBOSS集成的ActiveMQ处理消息

上篇博客对JBOSS和ActiveMQ集成做了一下实现,这篇用一个DEMO来看如何来用两者集成之后的ActiveMQ来处理消息。

 

这个DEMO是用STRUTS2+Spring3+MDB实现的,主要的功能是发送邮件。

首先来看邮件实体类:

packagecom.tgb.collegeplatform.common.email.util;
 
import java.io.Serializable;
import java.util.List;
 
 
/**
 * 邮件实体类
 *@author CJQ
 *2013-4-17 19:52
 */
@SuppressWarnings("serial")
public class Email implements Serializable{
 
         //收件人邮箱地址
         privateString to;
        
         //发件人邮箱地址
         privateString form;
 
         //SMTP服务器地址
         privateString smtpServer;
 
         //登录SMTP服务器的用户名
         privateString username;
 
         //登录SMTP服务器的密码
         privateString password;
 
         //邮件主题
         privateString subject;
 
         //邮件正文
         privateString content;
 
         //记录所有附件文件的集合
         privateList<String> attachments;
        
         publicEmail() {
                   super();
         }
        
        
         /**
          * 初始化各属性的构造器
          * @param to 指定收件人地址
          * @param form 指定发件人地址
          * @param smtpServer 指定SMTP服务器
          * @param username 指定登录SMTP服务器用户名
          * @param password 指定登录SMTP服务器密码
          * @param subject 邮件标题
          * @param content 邮件内容
          * @author CJQ
          * 2013-4-17 19:55
          */
         publicEmail(String to, String form, String smtpServer, String username,
                            Stringpassword, String subject, String content) {
                   this.to= to;
                   this.form= form;
                   this.smtpServer= smtpServer;
                   this.username= username;
                   this.password= password;
                   this.subject= subject;
                   this.content= content;
         }
 
 
         publicString getTo() {
                   returnto;
         }
 
         publicvoid setTo(String to) {
                   this.to= to;
         }
 
         publicString getForm() {
                   returnform;
         }
 
         publicvoid setForm(String form) {
                   this.form= form;
         }
 
         publicString getSmtpServer() {
                   returnsmtpServer;
         }
 
         publicvoid setSmtpServer(String smtpServer) {
                   this.smtpServer= smtpServer;
         }
 
         publicString getUsername() {
                   returnusername;
         }
 
         publicvoid setUsername(String username) {
                   this.username= username;
         }
 
         publicString getPassword() {
                   returnpassword;
         }
 
         publicvoid setPassword(String password) {
                   this.password= password;
         }
 
         publicString getSubject() {
                   returnsubject;
         }
 
         publicvoid setSubject(String subject) {
                   this.subject= subject;
         }
 
         publicString getContent() {
                   returncontent;
         }
 
         publicvoid setContent(String content) {
                   this.content= content;
         }
 
         publicList<String> getAttachments() {
                   returnattachments;
         }
 
         publicvoid setAttachments(List<String> attachments) {
                   this.attachments= attachments;
         }
        
         /**
          * 添加附件,即那个附件的文件名添加到list集合中
          * @param fanme 附件文件名
          * @author CJQ
          * 2013-4-17 20:07
          */
         publicvoid attachfile(String fanme){
                   attachments.add(fanme);
         }
}


 

之后我们来看MDB代码:

packagecom.tgb.collegeplatform.common.getandsendmail;
 
import java.util.Date;
import java.util.Properties;
 
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
importorg.jboss.ejb3.annotation.ResourceAdapter;
 
import com.tgb.collegeplatform.common.email.util.Email;
 
/**
 *Message-Driven Bean implementation class for: GetAndSendMail
 *
 */
@MessageDriven(activationConfig = {
                   @ActivationConfigProperty(propertyName= "destinationType", propertyValue = "javax.jms.Queue"),
                   @ActivationConfigProperty(propertyName= "destination", propertyValue = "queue.outbound") })
@ResourceAdapter("activemq-ra-5.7.0.rar")
public class GetAndSendMail implementsMessageListener {
 
         /**
          * Default constructor.
          */
         publicGetAndSendMail() {
         }
 
         /**
          * @see MessageListener#onMessage(Message)
          */
         publicvoid onMessage(Message message) {
 
                   if(message instanceof ObjectMessage) {
                            ObjectMessagemessageInfo = (ObjectMessage) message;
                            try{
                                     Emailemail = (Email) messageInfo.getObject();
                                     //判断是否需要身份认证
                                     MyAuthenticatorauthenticator = null;
                                     Propertiespro = new Properties();
                                     pro.put("mail.smtp.host",email.getSmtpServer());
                                     pro.put("mail.smtp.auth","true");
 
                                     //身份认证,则创建一个密码验证器
                                     authenticator= new MyAuthenticator(email.getUsername(),
                                                        email.getPassword());
 
                                     //根据邮件会话属性和密码验证器构造一个发送邮件的session
                                     SessionsendMailSession = Session.getDefaultInstance(pro,
                                                        authenticator);
 
                                     //根据session创建一个邮件消息
                                     javax.mail.MessagemailMessage = new MimeMessage(
                                                        sendMailSession);
                                     //创建邮件发送者地址
                                     Addressfrom = new InternetAddress(email.getForm());
                                     //设置邮件消息的发送者
                                     mailMessage.setFrom(from);
                                     //创建邮件的接收者地址,并设置到邮件消息中
                                     Addressto = new InternetAddress(email.getTo());
                                     mailMessage.setRecipient(javax.mail.Message.RecipientType.TO,
                                                        to);
                                     //设置邮件消息的主题
                                     mailMessage.setSubject(email.getSubject());
                                     //设置邮件消息发送的时间
                                     mailMessage.setSentDate(newDate());
                                     //设置邮件消息的主要内容
                                     StringmailContent = email.getContent();
                                     mailMessage.setText(mailContent);
                                     //发送邮件
                                     Transport.send(mailMessage);
                            }catch (MessagingException | JMSException ex) {
                                     ex.printStackTrace();
                            }
                   }
         }
 
         classMyAuthenticator extends Authenticator {
                   StringuserName = null;
                   Stringpassword = null;
 
                   publicMyAuthenticator() {
                   }
 
                   publicMyAuthenticator(String username, String password) {
                            this.userName= username;
                            this.password= password;
                   }
 
                   protectedPasswordAuthentication getPasswordAuthentication() {
                            returnnew PasswordAuthentication(userName, password);
                   }
         }
 
}


 

由于是EJB3的消息驱动Bean,所以利用注解来说明消息的配置信息—消息目的地的类型和消息目的地。另外需要用@ResourceAdapter注解指定ActiveMQ。

MDB的作用就是作为消息的消费者,在这个DEMO中MDB作为接受一个对象消息(EMAIL),之后把这个EMAIL的内容以email的形式发送出去。

 

之后我们来看客户端:

关于struts和spring的整合我就不介绍了,直接说spring如何管理ActiveMQ的:

<!-- Spring管理Struts2的Action -->
    <bean name="sendMailAction" class="com.tgb.collegeplatform.sendemail.action.SendMailAction"scope="prototype">
       <property name="queueConnectionFactory" ref="queueConnectionFactory"></property>
       <property name="queue" ref="queue"></property>
    </bean>
 
    <bean id="queueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
       <property name="jndiName" value="java:activemq/QueueConnectionFactory"></property>
    </bean>
    <bean id="queue" class="org.springframework.jndi.JndiObjectFactoryBean">
       <property name="jndiName" value="activemq/queue/outbound"></property>
    </bean>
 


因为MDB在ejb容器启动的时候就会向JNDI中注册一下,所以我们就用Spring来管理JNDI,通过JNDI来查找我们的消息目的地。

具体的Action代码:

package com.tgb.collegeplatform.sendemail.action;
 
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.jms.Session;
 
import com.opensymphony.xwork2.ActionSupport;
import com.tgb.collegeplatform.common.email.util.Email;
 
 
/**
 * 修改角色Action
 * @author CJQ
 * 2012-4-4 19:26
 */
@SuppressWarnings("serial")
public class SendMailAction extends ActionSupport {
 
         privateQueueConnectionFactory queueConnectionFactory;
        
         private Queue queue;
 
         publicQueueConnectionFactory getQueueConnectionFactory() {
                   returnqueueConnectionFactory;
         }
 
 
         public voidsetQueueConnectionFactory(
                            QueueConnectionFactoryqueueConnectionFactory) {
                   this.queueConnectionFactory= queueConnectionFactory;
         }
 
 
         public Queue getQueue() {
                   return queue;
         }
 
 
         public void setQueue(Queuequeue) {
                   this.queue =queue;
         }
 
 
         public String sendmail(){
                  
                   Email email=newEmail();
                   email.setContent("您好");
                   email.setForm("gaoxiaotgb@163.com");
                   email.setPassword("××××");
                   email.setUsername("gaoxiaotgb@163.com");
                   email.setSubject("测试");
                   email.setTo("gaoxiaotgb@163.com");
                   email.setSmtpServer("smtp.163.com");
                  
                   try {
                            Connectioncon = queueConnectionFactory.createConnection();
                            Sessionsession = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
                            MessageProducerproducer = session.createProducer(queue);
                            ObjectMessageobjectMessage = session.createObjectMessage();
                            objectMessage.setObject(email);
                            producer.send(objectMessage);
                            producer.close();
                            session.close();
                            con.close();
                   } catch(JMSException e) {
                            e.printStackTrace();
                   }
                   return"addSuccess";
         }
}
 


运行就会看到邮箱中收到了一份邮件。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值