ActiveMQ
摘自 ----OutOfMemory.CN技术专栏-> Java-> Java MQ-> Apache activemq入门示例(maven项目)
首先请到官网下载activemq,我下载的是activemq5.5.0,您可以根据需要下载自己想要的版本。我使用ubuntu系统,下载的是linux版本tar.gz后缀的文件。
下载之后解压到某个目录,然后将目录切换到解压后的目录,然后执行下面命令来启动activemq
bin/activemq start
正常启动的话,就可以到http://localhost:8161/admin/这个地址看mq管理后台了,在管理后台我们可以看到所有的queue,所有的topic以及所有的连接。您可以来回点一点了解一下mq后台的功能。
下面我们在代码中和activemq打个交道吧。
请新建一个maven项目,在pom.xml中添加如下依赖:
<?xml version="1.0" encoding="UTF-8"?> <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>cn.outofmemory</groupId> <artifactId>activemq-demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- activemq 相关maven依赖 --> <dependency> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> <version>1.1</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.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies> </project>
依赖分两部分前三个是activemq相关的maven依赖,后三个是日志相关的,都是不可或缺的,日志的你可以选择自己想要的。
下面我们在项目中新建一个类ProducerApp,顾名思义这个类是一个生产者,我们让这个类来向mq中生产消息。如下此类的实现,请注意注释部分的说明。
package cn.outofmemory.activemq.demo; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jms.*; /** * Created by outofmemory.cn on 14-8-26. * * activemq 生产者实例 */ public class ProducerApp { private static final Logger LOGGER = LoggerFactory.getLogger(ProducerApp.class); private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL; private static final String SUBJECT = "test-activemq-queue"; public static void main(String[] args) throws JMSException { //初始化连接工厂 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL); //获得连接 Connection conn = connectionFactory.createConnection(); //启动连接 conn.start(); //创建Session,此方法第一个参数表示会话是否在事务中执行,第二个参数设定会话的应答模式 Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); //创建队列 Destination dest = session.createQueue(SUBJECT); //createTopic方法用来创建Topic //session.createTopic("TOPIC"); //通过session可以创建消息的生产者 MessageProducer producer = session.createProducer(dest); for (int i=0;i<100;i++) { //初始化一个mq消息 TextMessage message = session.createTextMessage("hello active mq 中文" + i); //发送消息 producer.send(message); LOGGER.