1,使用SSM整合activemq,实现发送邮件的小案例。
可能涉及到其他方面的东西,不过很简单。
2,所需jar:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${srping.version}</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>4.2</version>
</dependency>
2,配置文件: spring-actviemq.xml
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
<bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="${activemq.url}"/>
<property name="userName" value="${activemq.username}"/>
<property name="password" value="${activemq.password}"/>
</bean>
<!-- spring管理的connectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="activeMQConnectionFactory"/>
<property name="sessionCacheSize" value="100" />
</bean>
<!-- jmsTemplate队列点对点模式 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<constructor-arg ref="connectionFactory"/>
<!-- 有好多属性,不是必须配置,个人认为在代码中指定方便-->
<!-- <property name="defaultDestination" ref="firstQueueDestination"/> -->
</bean>
<!-- 点对点类型-->
<bean id="firstQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="first"/> <!--queue的名字-->
</bean>
<!--订阅发布类型-->
<bean id="firstTopicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="first"/> <!--广播/topic的名字-->
</bean>
<!-- 监听器 -->
<!-- acknowledge:消息的确认 destination-type:目的地类型 -->
<jms:listener-container acknowledge="auto" container-type="default" destination-type="queue" connection-factory="connectionFactory">
<!-- destination: 目的地,mailListener的名字-->
<jms:listener destination="qq-mail" ref="mailListener"/>
</jms:listener-container>
3,因涉及javaMail:
javaMail相关jar包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
spring-javamail.xml
<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.username}"/>
</bean>
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.smtp.host}"/>
<property name="port" value="${mail.smtp.port}"/>
<property name="username" value="${mail.username}"/>
<property name="password" value="${mail.password}"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.debug">true</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
</props>
</property>
</bean>
<!--配置线程池-->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="${executor.corePoolSize}" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="${executor.maxPoolSize}" />
<!-- 最大队列数 -->
<property name="queueCapacity" value="${executor.queueCapacity}" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="${executor.keepAliveSeconds}" />
</bean>
application.properties部分配置信息:
## activemq config
activemq.url=tcp://ip:61616
activemq.username=你的用户名
activemq.password=你的密码
## javaMail config
mail.smtp.host=smtp.163.com
mail.smtp.port=25
mail.username=xxxx@163.com
mail.password=你的邮箱密码
mail.smtp.auth=true
mail.smtp.timeout=30000
## 线程池 config
executor.corePoolSize=4
executor.maxPoolSize=32
executor.queueCapacity=128
executor.keepAliveSeconds=60
4,实体类:MailContent.java
public class MailContent implements Serializable{
/**
* 收件人
*/
private String recipients;
/**
* 抄送人
*/
private String carbonCopy;
/**
* 主题
*/
private String subject;
/**
* 内容
*/
private String text;
public MailContent() {
// TODO Auto-generated constructor stub
}
public MailContent(String recipients, String subject, String text) {
super();
this.recipients = recipients;
this.subject = subject;
this.text = text;
}
public MailContent(String recipients, String carbonCopy, String subject, String text) {
super();
this.recipients = recipients;
this.carbonCopy = carbonCopy;
this.subject = subject;
this.text = text;
}
public String getRecipients() {
return recipients;
}
public void setRecipients(String recipients) {
this.recipients = recipients;
}
public String getCarbonCopy() {
return carbonCopy;
}
public void setCarbonCopy(String carbonCopy) {
this.carbonCopy = carbonCopy;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "MailContent [recipients=" + recipients + ", carbonCopy=" + carbonCopy + ", subject=" + subject
+ ", text=" + text + "]";
}
}
5,QueueProducerService.java
public interface QueueProducerService {
/**
* 发送queue消息
* @param msg
* @return
*/
public void sendTextMessage(MailContent mailContent);
/**
* 发送邮件
* @param mailContent 邮件实体
*/
public void sendMail(MailContent mailContent);
}
QueueProducerSerivceImpl.java
@Service("queueProducerService")
public class QueueProducerSerivceImpl implements QueueProducerService {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private SimpleMailMessage simpleMailMessage;
@Autowired
private TaskExecutor taskExecutor;
@Override
public void sendTextMessage(MailContent mailContent) {
mailContent.setCarbonCopy("18307200213@163.com");
//设置发送地址
this.jmsTemplate.setDefaultDestinationName("qq-mail");
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createObjectMessage(mailContent);
}
});
}
/**
* 发送邮件
* @param mailContent
*/
public void sendMail(MailContent mailContent) {
System.out.println("sendMail--------mailContent-----"+mailContent);
try {
this.simpleMailMessage.setFrom(mailContent.getCarbonCopy());
this.simpleMailMessage.setSubject(mailContent.getSubject());
StringBuffer messageText=new StringBuffer(); //内容以html格式发送,防止被当成垃圾邮件
messageText.append("Hi,你好,这是不哭死神的测试用例,").append("此测试用例的内容为:"+mailContent.getText());
this.simpleMailMessage.setText("<h2>"+messageText.toString()+"</h2>");
this.simpleMailMessage.setTo(mailContent.getRecipients());
//javaMailSender.send(simpleMailMessage);
addSendMailTask(simpleMailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @desc 使用多线程发送邮件
* @param message MimeMessage邮件封装类
*/
private void addSendMailTask(final SimpleMailMessage message){
try{
taskExecutor.execute(new Runnable() {
@Override
public void run() {
javaMailSender.send(message);
System.out.println("邮件已发送!");
}
});
}catch (Exception e){
System.out.println("邮件发送异常,邮件详细信息为:"+e.getMessage());
}finally {
}
}
}
MailMessageListener.java
@Component("mailListener") //必须和spring-activemq.xml配置的监听器名称一致
public class MailMessageListener implements MessageListener {
@Autowired
private QueueProducerService queueProducerService;
@Override
public void onMessage(Message message) {
try {
if(message instanceof ObjectMessage) {
ObjectMessage om = (ObjectMessage)message;
Object data = om.getObject();
if(data instanceof MailContent) {
MailContent mc= (MailContent)data;
queueProducerService.sendMail(mc);
}
}else {
System.out.println( message );
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
Controller代码
@RequestMapping("base")
@Controller("baseController")
public class BaseController {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private QueueProducerService messageService;
@ResponseBody
@RequestMapping("send")
public String redis(String from,String to,String subject,String text) {
if(StringUtils.isBlank(to) || StringUtils.isBlank(subject) || StringUtils.isBlank(text) ) {
return JSONResult.failCreate("发送失败", "").toJSON();
}
MailContent mailContent = new MailContent(to,subject,text);
System.out.println("baseController--------mailContent-----"+mailContent);
messageService.sendTextMessage(mailContent);
return JSONResult.create("发送成功").toJSON();
}
}
index.html
<h2>发送邮件</h2>
<form action="../base/send.do" method="post">
收件人:<input type="text" name="to"/><br>
主题:<input type="text" name="subject"/><br>
内容:<input type="text" name="text"/><br>
<input type="submit" value="发送">
</form>