`

ActiveMQ的安装与使用\ActiveMQ的使用代码样例(消费者)

阅读更多
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>wusc.edu.common</groupId>
		<artifactId>edu-common-parent</artifactId>
		<version>1.0-SNAPSHOT</version>
		<relativePath>../edu-common-parent</relativePath>
	</parent>

	<groupId>com.fsbay.mqtest</groupId>
	<artifactId>edu-demo-mqconsumer</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>edu-demo-mqconsumer</name>
	<url>http://maven.apache.org</url>

	<build>
		<finalName>edu-demo-mqconsumer</finalName>
		<resources>
			<resource>
				<targetPath>${project.build.directory}/classes</targetPath>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
		</resources>
	</build>

	<dependencies>

		<!-- Common Dependency Begin -->
		<dependency>
			<groupId>antlr</groupId>
			<artifactId>antlr</artifactId>
		</dependency>
		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<classifier>jdk15</classifier>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ognl</groupId>
			<artifactId>ognl</artifactId>
		</dependency>
		<dependency>
			<groupId>oro</groupId>
			<artifactId>oro</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-validator</groupId>
			<artifactId>commons-validator</artifactId>
		</dependency>
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
		</dependency>

		<!-- Common Dependency End -->

		<!-- Spring Dependency Begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>

		<!-- Spring Dependency End -->


		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-all</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>


	</dependencies>


</project>



package com.fsbay.demo.mqtest.biz;

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.Component;

import com.fsbay.demo.mqtest.params.MailParam;


/**
 * 
 * @描述: 邮件发送业务逻辑类 .
 * @作者: john .
 * @创建时间: 2015-3-18,上午1:08:22 .
 * @版本号: V1.0 .
 */
@Component("mailBiz")
public class MailBiz {

	@Autowired
	private JavaMailSender mailSender;// spring配置中定义
	@Autowired
	private SimpleMailMessage simpleMailMessage;// spring配置中定义
	@Autowired
	private ThreadPoolTaskExecutor threadPool;

	/**
	 * 发送模板邮件
	 * 
	 * @param mailParamTemp需要设置四个参数
	 *            templateName,toMail,subject,mapModel
	 * @throws Exception
	 * 
	 */
	public void mailSend(final MailParam mailParam) {
		threadPool.execute(new Runnable() {
			public void run() {
				try {
					simpleMailMessage.setFrom(simpleMailMessage.getFrom()); // 发送人,从配置文件中取得
					simpleMailMessage.setTo(mailParam.getTo()); // 接收人
					simpleMailMessage.setSubject(mailParam.getSubject());
					simpleMailMessage.setText(mailParam.getContent());
					mailSender.send(simpleMailMessage);
				} catch (MailException e) {
					throw e;
				}
			}
		});
	}
}


package com.fsbay.demo.mqtest.listener;

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

import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;

import com.fsbay.demo.mqtest.biz.MailBiz;
import com.fsbay.demo.mqtest.params.MailParam;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @描述: 队列监听器 .
 * @作者: John .
 * @创建时间: 2015-3-17,下午11:21:23 .
 * @版本号: V1.0 .
 */
@Component
public class ConsumerSessionAwareMessageListener implements SessionAwareMessageListener<Message> {

	private static final Log log = LogFactory.getLog(ConsumerSessionAwareMessageListener.class);

	@Autowired
	private JmsTemplate activeMqJmsTemplate;
	@Autowired
	private Destination sessionAwareQueue;
	@Autowired
	private MailBiz bailBiz;

	public synchronized void onMessage(Message message, Session session) {
		try {
			ActiveMQTextMessage msg = (ActiveMQTextMessage) message;
			final String ms = msg.getText();
			log.info("==>receive message:" + ms);
			MailParam mailParam = JSONObject.parseObject(ms, MailParam.class);// 转换成相应的对象
			if (mailParam == null) {
				return;
			}

			try {
				bailBiz.mailSend(mailParam);
			} catch (Exception e) {
				// 发送异常,重新放回队列
//				activeMqJmsTemplate.send(sessionAwareQueue, new MessageCreator() {
//					public Message createMessage(Session session) throws JMSException {
//						return session.createTextMessage(ms);
//					}
//				});
				log.error("==>MailException:", e);
			}
		} catch (Exception e) {
			log.error("==>", e);
		}
	}
}



package com.fsbay.demo.mqtest.params;

/**
 * 
 * @描述: 邮件参数封装类 .
 * @作者: john .
 * @创建时间: 2015-3-18,上午1:08:42 .
 * @版本号: V1.0 .
 */
public class MailParam {

	/** 发件人 **/
	private String from;
	/** 收件人 **/
	private String to;
	/** 主题 **/
	private String subject;
	/** 邮件内容 **/
	private String content;

	public MailParam() {
	}

	public MailParam(String to, String subject, String content) {
		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;
	}
}



package com.fsbay.demo.mqtest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 
 * @描述: ActiveMQ测试启动类  .
 * @作者: john .
 * @创建时间: 2015-3-17,上午2:25:20 .
 * @版本号: V1.0 .
 */
public class MQConsumer {
	private static final Log log = LogFactory.getLog(MQConsumer.class);

	public static void main(String[] args) {
		try {
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");
			context.start();
		} catch (Exception e) {
			log.error("==>MQ context start error:", e);
			System.exit(0);
		}
	}
}


<?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">
	

	<!-- 采用注释的方式配置bean -->
	<context:annotation-config />

	<!-- 配置要扫描的包 -->
	<context:component-scan base-package="wusc.edu.demo" />

	<!-- 读入配置属性文件 -->
	<context:property-placeholder location="classpath:mq.properties,classpath:mail.properties" />

	<!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />	
	
	<import resource="spring-mq.xml" />
	<import resource="spring-mail.xml" />
	
</beans>

<?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>

<?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">

	<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
		<!-- ActiveMQ服务地址 -->
        <property name="brokerURL" value="${mq.brokerURL}" />
        <property name="userName" value="${mq.userName}"></property>
        <property name="password" value="${mq.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="${mq.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="activeMqJmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
	    <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->  
	    <property name="connectionFactory" ref="connectionFactory"/>  
	    <property name="defaultDestinationName" value="${queueName}"></property>
	</bean> 
	
	<!--这个是sessionAwareQueue目的地 -->
	<bean id="sessionAwareQueue" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg>
			<value>${queueName}</value>
		</constructor-arg>
	</bean>

	<!-- 可以获取session的MessageListener -->
	<bean id="consumerSessionAwareMessageListener" class="wusc.edu.demo.mqtest.listener.ConsumerSessionAwareMessageListener"></bean>

	<bean id="sessionAwareListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
		<property name="connectionFactory" ref="connectionFactory" />
		<property name="destination" ref="sessionAwareQueue" />
		<property name="messageListener" ref="consumerSessionAwareMessageListener" />
	</bean>

</beans>

#SMTP服务配置
mail.host=smtp.qq.com
mail.port=25
mail.username=XXX@qq.com
mail.password=XXXX
mail.smtp.auth=true
mail.smtp.timeout=30000
mail.default.from=XXXXX@qq.com


## MQ
mq.brokerURL=tcp\://192.168.4.101\:61616
mq.userName=john
mq.password=john.123
mq.pool.maxConnections=10
#queueName
queueName=wusc.edu.mqtest.v1
分享到:
评论

相关推荐

    ActiveMQ的使用代码样例(异步邮件发送).rar

    总结来说,这个"ActiveMQ的使用代码样例(异步邮件发送)"提供了如何利用ActiveMQ实现异步通信的实际例子,特别在邮件服务场景中。通过理解这些关键概念和技术,开发者可以有效地构建自己的分布式系统,提高应用的...

    JMS+ActiveMQ 完整样例代码

    3. **ActiveMQ的配置与使用**:了解如何在代码中配置ActiveMQ连接工厂,创建会话,创建生产者和消费者对象,以及如何设置消息属性。此外,你还将学习如何使用ActiveMQ的管理工具来查看和管理消息队列和主题。 4. **...

    activemq测试样例

    这个“activemq测试样例”压缩包提供了有关如何使用ActiveMQ创建队列、创建消费者以及处理消息积压的示例。通过这个样例,我们可以深入了解ActiveMQ的基本操作和特性。 首先,我们要理解ActiveMQ中的队列。在JMS中...

    ActiveMQ的使用代码样例(异步邮件发送).zip

    消费者同样需要连接到ActiveMQ服务器,创建一个Session和MessageConsumer对象,然后监听指定队列上的消息。 ```java import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.Connection; import ...

    JMS+ActiveMQ+Spring 完整样例代码

    **JMS+ActiveMQ+Spring 完整样例代码详解** 在Java世界中,消息队列(Message Queue,简称MQ)是一种重要的中间件技术,它允许应用程序之间通过异步通信来解耦系统组件。Java消息服务(Java Message Service,简称...

    C# ActiveMQ 和Spring.NET框架开发示例

    在开发中,开发者需要将ActiveMQ与C#应用程序结合,使用***框架来开发消息队列系统,这涉及到配置连接工厂、队列目的地、消息监听器容器等组件,以及编写消息消费者和生产者的代码逻辑。 在C#应用程序中使用***框架...

    AMQ样例,参考

    在“AMQ样例”的标签下,我们可以期待这个WebActiveMQ_Demo包含了一系列示例代码、配置文件或者教程,帮助用户了解如何创建和管理消息、如何设置消费者和生产者、以及如何实现消息的可靠传输和持久化等。 在...

    JMS简单示例1

    在JMS中,消息是数据传输的载体,而消息生产者和消费者通过消息中间件(如消息队列或主题)进行通信。 **JMS核心概念** 1. **消息(Message)**:JMS中的基本数据单元,包含数据和元数据(如目标地址、优先级等)...

    jms整合spring工程

    **正文** ...总的来说,"jms整合spring工程"是一个实用的示例,帮助开发者理解和实践在Spring中使用JMS与ActiveMQ进行消息通信。通过深入研究该项目,可以掌握JMS和Spring集成的关键技术和最佳实践。

    登录linux执行命令

    1. **AMQ连接**:设置AMQ客户端,创建消费者监听指定队列,等待接收消息。 2. **消息处理**:接收到消息后,解码并解析出命令内容。 3. **SSH登录**:使用expect4j库建立SSH连接,可能需要提供服务器地址、用户名、...

Global site tag (gtag.js) - Google Analytics