1. 程式人生 > >ActiveMQ與Spring的整合之非同步傳送電子郵件

ActiveMQ與Spring的整合之非同步傳送電子郵件

1、ActiveMQ與Spring整合,訊息生產方的程式碼

      1.1    專案的目錄


      1.2   config.properties 

## ActiveMQ Config
activemq.brokerURL=tcp\://192.168.2.104\:61616
activemq.userName=zhangsan
activemq.password=123
activemq.pool.maxConnections=10
#queueName 
activemq.queueName=mailqueue

      1.3   spring-activemq.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
           http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
           http://www.springframework.org/schema/tx  
           http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.2.xsd"
	default-autowire="byName" default-lazy-init="false">

	<!-- 第三方MQ工廠: ConnectionFactory -->
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
		<!-- ActiveMQ Address -->
		<property name="brokerURL" value="${activemq.brokerURL}" />
		<property name="userName" value="${activemq.userName}"></property>
		<property name="password" value="${activemq.password}"></property>
	</bean>

	<!-- ActiveMQ為我們提供了一個PooledConnectionFactory,通過往裡面注入一個ActiveMQConnectionFactory 
		可以用來將Connection、Session和MessageProducer池化,這樣可以大大的減少我們的資源消耗,要依賴於 activemq-pool包 -->
	<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
		<property name="connectionFactory" ref="targetConnectionFactory" />
		<property name="maxConnections" value="${activemq.pool.maxConnections}" />
	</bean>

	<!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
	<bean id="connectionFactory"
		class="org.springframework.jms.connection.SingleConnectionFactory">
		<!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
		<property name="targetConnectionFactory" ref="pooledConnectionFactory" />
	</bean>
	<!--這個是目的地:mailQueue -->
	<!-- 使用Queue方式  -->
	<!-- <bean id="mailQueue" class="org.apache.activemq.command.ActiveMQQueue"/> -->
	<!-- 使用Topic方式 -->
	<bean id="mailQueue" class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg>
			<value>${activemq.queueName}</value>
		</constructor-arg>
	</bean>
	<!-- Spring提供的JMS工具類,它可以進行訊息傳送、接收等 -->
	<!-- 佇列模板 -->
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<!-- 這個connectionFactory對應的是我們定義的Spring提供的那個ConnectionFactory物件 -->
		<property name="connectionFactory" ref="connectionFactory" />
		<property name="defaultDestination" ref="mailQueue"></property>
	</bean>

</beans>

      1.4   spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
           http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
           http://www.springframework.org/schema/tx  
           http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.2.xsd"
	default-autowire="byName" default-lazy-init="false">
	
	<!-- 讀入配置屬性檔案 -->
	<context:property-placeholder location="classpath:config.properties" />
	
	<!-- 註釋配置 -->
	<context:annotation-config />

	<!-- 掃描包起始位置 -->
	<context:component-scan base-package="bhz" />

	<import resource="classpath:spring-activemq.xml" />
</beans>

      1.5   log4j.properties

log4j.rootLogger=INFO, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.file.File=D:/002_developer/workspace_001/zcmoni.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.logger.org.springframework=WARN

         1.6  Mail.java的程式碼
public class Mail {

	/** 發件人 **/
	private String from;
	/** 收件人 **/
	private String to;
	/** 主題 **/
	private String subject;
	/** 郵件內容 **/
	private String content;
	
	public Mail(){}
	
	public Mail(String from, String to, String subject, String content) {
		super();
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.content = content;
	}
	
	public String getFrom() {
		return from;
	}
	public void setFrom(String from) {
		this.from = from;
	}
	public String getTo() {
		return to;
	}
	public void setTo(String to) {
		this.to = to;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
}
          1.7  MQProducer.java的程式碼 
@Service("mqProducer")
public class MQProducer {

	private JmsTemplate jmsTemplate;

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	@Autowired
	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	/**
	 * <B>方法名稱:</B>傳送郵件資訊物件<BR>
	 * <B>概要說明:</B>傳送郵件資訊物件<BR>
	 * 
	 * @param mail
	 */
	public void sendMessage(final Mail mail) {
		jmsTemplate.send(new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(JSONObject.toJSONString(mail));
			}
		});
	}

}

          1.8  TestProducer.java的程式碼

@ContextConfiguration(locations = { "classpath:spring-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestProducer {

	@Autowired
	private MQProducer mqProducer;

	@Test
	public void send() {
		Mail mail = new Mail();
		mail.setTo("[email protected]");
		mail.setSubject("非同步傳送郵件");
		mail.setContent("Hi,This is a message!");

		this.mqProducer.sendMessage(mail);
		System.out.println("傳送成功..");

	}

}

          1.9   pom.xml的檔案

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>activemq</groupId>
	<artifactId>activemq-provider</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<!-- 設定公共屬性,可以被引用 ${attribute} -->
	<!-- 設定公共屬性,可以被引用 ${attribute} -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<junit.version>4.11</junit.version>
		<spring.version>3.2.3.RELEASE</spring.version>
		<httpclient.version>4.3.1</httpclient.version>
	</properties>


	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.1.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-all</artifactId>
			<version>5.11.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
			<version>5.11.1</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>0.2.9</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.1</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.11</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3.2</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.26</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.10</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jul-to-slf4j</artifactId>
			<version>1.7.6</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.7.5</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>


		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>activemq-provider</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>utf8</encoding>
				</configuration>
			</plugin>

		</plugins>
	</build>
</project>

2、ActiveMQ與Spring整合,訊息消費方的程式碼

        2.1    專案的目錄


        2.2    Mail.java 見上面

        2.3    MailQueueMessageListener.java 實現非同步傳送訊息的監聽器,很重要

import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;

import bhz.entity.Mail;
import bhz.service.MailService;

import com.alibaba.fastjson.JSONObject;

@Component
public class MailQueueMessageListener implements
		SessionAwareMessageListener<Message> {

	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private Destination mailQueue;
	@Autowired
	private MailService mailService;

	public synchronized void onMessage(Message message, Session session) {
		try {
			TextMessage msg = (TextMessage) message;
			final String ms = msg.getText();
			System.out.println("收到訊息:" + ms);
			// 轉換成相應的物件
			Mail mail = JSONObject.parseObject(ms, Mail.class);
			if (mail == null) {
				return;
			}
			try {
				// 執行傳送業務
				mailService.mailSend(mail);

			} catch (Exception e) {
				// 傳送異常,重新放回佇列
				// jmsTemplate.send(mailQueue, new MessageCreator() {
				// @Override
				// public Message createMessage(Session session) throws
				// JMSException {
				// return session.createTextMessage(ms);
				// }
				// });
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

        2.4    log4j.properties 見上面

        2.5    config.properties   加入了郵箱相關的配置(用的是163郵箱)

## ActiveMQ Configuration
activemq.brokerURL=tcp\://192.168.2.104\:61616
activemq.userName=zhangsan
activemq.password=123
activemq.pool.maxConnections=10
#queueName
activemq.queueName=mailqueue

## SMTP Configuration
mail.host=smtp.163.com
##mail.port=21
mail.username= 填寫自己的163郵箱地址
mail.password= 填寫自己的163郵箱密碼
mail.smtp.auth=true
mail.smtp.timeout=30000
mail.default.from=填寫自己的163郵箱地址

        2.6    spring-activemq.xml   與上面的區別,主要在於加入了監聽器,用於非同步消費訊息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
           http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
           http://www.springframework.org/schema/tx  
           http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.2.xsd"
	default-autowire="byName" default-lazy-init="false">


	<!-- 第三方MQ工廠: ConnectionFactory -->
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
		<!-- ActiveMQ服務地址 -->
		<property name="brokerURL" value="${activemq.brokerURL}" />
		<property name="userName" value="${activemq.userName}"></property>
		<property name="password" value="${activemq.password}"></property>
	</bean>

	<!-- ActiveMQ為我們提供了一個PooledConnectionFactory,通過往裡面注入一個ActiveMQConnectionFactory 
		可以用來將Connection、Session和MessageProducer池化,這樣可以大大的減少我們的資源消耗,要依賴於 activemq-pool包 -->
	<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
		<property name="connectionFactory" ref="targetConnectionFactory" />
		<property name="maxConnections" value="${activemq.pool.maxConnections}" />
	</bean>

	<!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
	<bean id="connectionFactory"
		class="org.springframework.jms.connection.SingleConnectionFactory">
		<!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
		<property name="targetConnectionFactory" ref="pooledConnectionFactory" />
	</bean>

	<!-- Spring提供的JMS工具類,它可以進行訊息傳送、接收等 -->

	<!-- 佇列模板 -->
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<!-- 這個connectionFactory對應的是我們定義的Spring提供的那個ConnectionFactory物件 -->
		<property name="connectionFactory" ref="connectionFactory" />
		<property name="defaultDestinationName" value="${activemq.queueName}"></property>
	</bean>

	<!--這個是目的地:mailQueue -->
        <!-- <bean id="mailQueue" class="org.apache.activemq.command.ActiveMQQueue/"/> -->
	<bean id="mailQueue" class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg>
			<value>${activemq.queueName}</value>
		</constructor-arg>
	</bean>

	<!-- 配置自定義監聽:MessageListener -->
	<bean id="mailQueueMessageListener" class="bhz.mq.MailQueueMessageListener"></bean>

	<!-- 將連線工廠、目標對了、自定義監聽注入jms模板 -->
	<bean id="sessionAwareListenerContainer"
		class="org.springframework.jms.listener.DefaultMessageListenerContainer">
		<property name="connectionFactory" ref="connectionFactory" />
		<property name="destination" ref="mailQueue" />
		<property name="messageListener" ref="mailQueueMessageListener" />
	</bean>

</beans>

        2.7    spring-mail.xml   傳送郵箱的配置

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
	   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
       
	
	<!-- Spring提供的傳送電子郵件的高階抽象類 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="${mail.host}" />
		<property name="username" value="${mail.username}" />
		<property name="password" value="${mail.password}" />
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
				<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
			</props>
		</property>
	</bean>

	<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="from">
			<value>${mail.default.from}</value>
		</property>
	</bean>
	
	<!-- 配置執行緒池 -->
	<bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<!-- 執行緒池維護執行緒的最少數量 -->
		<property name="corePoolSize" value="5" />
		<!-- 執行緒池維護執行緒所允許的空閒時間 -->
		<property name="keepAliveSeconds" value="30000" />
		<!-- 執行緒池維護執行緒的最大數量 -->
		<property name="maxPoolSize" value="50" />
		<!-- 執行緒池所使用的緩衝佇列 -->
		<property name="queueCapacity" value="100" />
	</bean>

</beans>

        2.8    spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
           http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
           http://www.springframework.org/schema/tx  
           http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.2.xsd"
	default-autowire="byName" default-lazy-init="false">

	<!-- 讀入配置屬性檔案 -->
	<context:property-placeholder location="classpath:config.properties" />
	
	<!-- 註釋配置 -->
	<context:annotation-config />

	<!-- 掃描包起始位置 -->
	<context:component-scan base-package="bhz" />

	<!-- proxy-target-class預設"false",更改為"ture"使用CGLib動態代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />	
	
	<import resource="classpath:spring-activemq.xml" />
	<import resource="classpath:spring-mail.xml" />
	
</beans>

        2.9    MailService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import bhz.entity.Mail;

@Service("mailService")
public class MailService {

	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private SimpleMailMessage simpleMailMessage;
	@Autowired
	private ThreadPoolTaskExecutor threadPool;

	/**
	 * <B>方法名稱:</B>傳送郵件<BR>
	 * <B>概要說明:</B>傳送郵件<BR>
	 * 
	 * @param mail
	 */
	public void mailSend(final Mail mail) {
		threadPool.execute(new Runnable() {
			public void run() {
				try {
					simpleMailMessage.setFrom(simpleMailMessage.getFrom());
					simpleMailMessage.setTo(mail.getTo());
					simpleMailMessage.setSubject(mail.getSubject());
					simpleMailMessage.setText(mail.getContent());
					// mailSender.send(simpleMailMessage);
					//mailSender.send(simpleMailMessage);
					//MimeMessage
					mailSender.send(simpleMailMessage);
				} catch (MailException e) {
					e.printStackTrace();
					throw e;
				}
			}
		});
	}
}

        2.10  TestConsumer.java

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestConsumer {

	public static void main(String[] args) {
		try {
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "spring-context.xml" });
			context.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3、程式碼下載

相關推薦

ActiveMQSpring整合非同步傳送電子郵件

1、ActiveMQ與Spring整合,訊息生產方的程式碼       1.1    專案的目錄       1.2   config.properties  ## ActiveMQ Config activemq.brokerURL=tcp\://192.168.2.

jmsactiveMQspring整合進階-實現一種負載均衡

="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd            http://www.springframe

ActiveMQspring整合

arc 整合 schema emp jar dep mqc and cti 第一步:引用相關的jar包 <dependency> <groupId>org.springframework</groupId

javaEE Mybatis,MybatisSpring整合傳統Dao開發(不推薦)。SqlSessionDaoSupport(Mybatis提供的Dao層基類)

src/applicationContext.xml(Spring核心配置檔案): <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.or

javaEE Mybatis,MybatisSpring整合動態代理方式(推薦),自動建立Dao層實現類

src/applicationContext.xml(Spring核心配置檔案): <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.or

javaEE ActiveMQActiveMQSpring整合

需要先安裝ActiveMQ服務,並啟動。 生產者: applicationContext.xml(Spring配置檔案,配置工廠,配置生產者): <?xml version="1.0" encoding="UTF-8"?> <beans xml

ActiveMQSpring整合:(3)訊息監聽器

        JMS監聽器有三種訊息監聽器實現:MessageListener,SessionAwareMessageListener,MessageListenerAdapter。訊息接受者只需要實現這些介面就可以非同步接收訊息。 1、實現MessageListener

13.Springboot JavaMailSender傳送電子郵件

在很多網站系統應用中,電子郵件的傳送應該非常常見,如:驗證碼傳送、密碼找回郵件傳送、事件通知郵件傳送等。 下面簡單介紹一下在Springboot的開發中如何使用JavaMailSender傳送電子郵件。 引入Maven依賴包 <dependency> <groupId>or

Springboot JavaMailSender傳送電子郵件

本文章來自【知識林】 在很多網站系統應用中,電子郵件的傳送應該非常常見,如:驗證碼傳送、密碼找回郵件傳送、事件通知郵件傳送等。 下面簡單介紹一下在Springboot的開發中如何使用JavaMail

activemq 學習系列(五) activemq spring boot 整合

-a pool autowire mapping pri control ESS fin tid activemq 與 spring boot 整合 1、添加依賴 <dependency> <groupId>

ActiveMQSpring進行整合

                                ActiveMQ與Spring進行整合   Activ

springhibernate整合sessionfactory的三種方式

方式1:只加載SessionFactory   <bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <propertyn

EhCache教程Hello World和Spring整合

一:目錄 EhCache 簡介 Hello World 示例 Spring 整合 二: 簡介 1. 基本介紹 EhCache 是一個純Java的程序內快取框架,具有快速、精幹等特點,是Hibernate中預設Cache

CXF系列JAX-RS:CXFspring整合釋出REST服務

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transition

04.ActiveMQSpring JMS整合

1.SpringJMS核心介面介紹 1.JmsTemplate JmsTemplate: 是Spring自身提供,只需向Spring容器內註冊這個類即可,就可以使用JmsTemplate類物件方便的操作JMS,下面介紹他常用的方法。     注意:JmsTemplate類是執行緒安全的,可以在整個應

JAVAWEB開發mybatis詳解(二)——高階對映、查詢快取、mybatisSpring整合以及懶載入的配置和逆向工程

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "ht

webservicecxf實現[web專案中基於mavenspring整合]

webservice現開發的已實現元件不少,使用過的就有xfire及cxf. cxc基於maven與spring整合過程如下: STEP 1. 依賴包新增 在pom.xml檔案的標籤中增加如下(版本號依個人需要調整): <depende

Spring BootLog4j2整合java.lang.IllegalStateException: Logback configuration error detected:

引言: 一個問題的分析與解決過程是表與裡的過程,是一個大膽猜測與小心求證的過程,spring boot與log4j2的整合過程中,我將描述一下分析這個問題的思路和過程。 我一直強調一點: 重要的不是解決問題的結論,而是解決問題的思路和方法,即使在解決完問題之後,

WebService學習旅(三)JAX-WSSpring整合釋出WebService

Spring本身就提供了對JAX-WS的支援,有興趣的讀者可以研究下Spring的Spring-WS專案,專案地址: http://docs.spring.io/spring-ws/sites/1.5/downloads/releases.html 基於Sp

Mybatis中Mapper代理形式開發spring整合

can sna 修改 jar xid oca pac user cal 1.導入jar包 2.分包 cogfig:存放配置文件 mapper:存放映射與接口 pojo:存放實體類 test:測試代碼 3.編寫配置文件 SqlMapConfig.xml <?