您的位置:首页 > 运维架构 > Linux

ActiveMq--00--Windows和Linux平台安装使用ActiveMQ

2017-11-09 15:39 323 查看
一、概述与介绍

ActiveMQ是Apache出品,最流行的、功能强大的即时通讯和集成模式的开源服务器。ActiveMQ是一个完全支持JMS1.1和J2EE1.4规范的JMSProvider实现。提供客户端支持跨语言和协议,带有易于在充分支持JMS1.1和1.4使用J2EE企业集成模式和许多先进的功能。

二、特性

1、多种语言和协议编写客户端。语言:Java、C、C++、C#、Ruby、Perl、Python、PHP。应用协议:OpenWire、StompREST、WSNotification、XMPP、AMQP

2、完全支持JMS1.1和J2EE1.4规范(持久化,XA消息,事务)

3、对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性

4、通过了常见J2EE服务器(如Geronimo、JBoss4、GlassFish、WebLogic)的测试,其中通过JCA1.5resourceadaptors的配置,可以让ActiveMQ可以自动的部署到任何兼容J2EE1.4商业服务器上

5、支持多种传送协议:in-VM、TCP、SSL、NIO、UDP、JGroups、JXTA

6、支持通过JDBC和journal提供高速的消息持久化

7、从设计上保证了高性能的集群,客户端-服务器,点对点

8、支持Ajax

9、支持与Axis的整合

10、可以很容易得调用内嵌JMSprovider,进行测试

三、安装

开发环境:

System:Windows

JDK:1.6+

IDE:eclipse

apacheActiveMQ5.8

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

1、下载ActiveMQ,下载地址:http://www.apache.org/dyn/closer.cgi?path=/activemq/apache-activemq/5.8.0/apache-activemq-5.8.0-bin.zip

2、解压apache-activemq-5.8.0.zip即可完成ActiveMQ的安装

3、解压后目录结构如下





+bin(windows下面的bat和unix/linux下面的sh)启动ActiveMQ的启动服务就在这里

+conf(activeMQ配置目录,包含最基本的activeMQ配置文件)

+data(默认是空的)

+docs(index,replease版本里面没有文档)

+example(几个例子)

+lib(activeMQ使用到的lib)

+webapps(系统管理员控制台代码)

+webapps-demo(系统示例代码)

-activemq-all-5.8.0.jar(ActiveMQ的binary)

-user-guide.html(部署指引)

-LICENSE.txt

-NOTICE.txt

-README.txt

其他文件就不相信介绍了,搞Java的应该都知道干什么用的。

你可以进入bin目录,使用activemq.bat双击启动(windows用户可以选择系统位数,如果你是linux的话,就用命令行的发送去启动),如果一切顺利,你就会看见类似下面的信息:





如果你看到这个,那么恭喜你成功了。如果你启动看到了异常信息:

Causedby:java.io.IOException:Failedtobindtoserversocket:tcp://0.0.0.0:61616?maximumConnections=1000&wireformat.maxFrameSize=104857600dueto:java.net.SocketException:UnrecognizedWindowsSocketserror:0:JVM_Bind

那么我告诉你,很不幸,你的端口被占用了。接下来你大概想知道是哪个程序占用了你的端口,并kill掉该进程或服务。或者你要尝试修改ActiveMQ的默认端口61616(ActiveMQ使用的默认端口是61616),在大多数情况下,占用61616端口的是InternetConnectionSharing(ICS)这个Windows服务,你只需停止它就可以启动ActiveMQ了。

4、启动成功就可以访问管理员界面:http://localhost:8161/admin,默认用户名和密码admin/admin。如果你想修改用户名和密码的话,在conf/jetty-realm.properties中修改即可。





其中在导航菜单中,Queues是队列方式消息。Topics是主题方式消息。Subscribers消息订阅监控查询。Connections可以查看链接数,分别可以查看xmpp、ssl、stomp、openwire、ws和网络链接。Network是网络链接数监控。Send可以发送消息数据。

5、运行demo示例,在dos控制台输入activemq.batxbean:../conf/activemq-demo.xml即可启动demo示例。官方提供的user-guide.html中的accessthewebconsole中是提示输入:activemq.bat
consolexbean:conf/activemq-demo.xml,我用这种方式不成功。

当然你还可以用绝对的文件目录方式:activemq.batxbean:file:D:/mq/conf/activemq-demo.xml





如果提示conf/activemq-demo.xml没有找到,你可以尝试改变下路径,也就是去掉上面的“..”。通过http://localhost:8161/demo/就可以访问示例了。





四、消息示例

1、ActiviteMQ消息有3中形式

JMS公共
点对点域
发布/订阅域
ConnectionFactory

QueueConnectionFactory

TopicConnectionFactory

Connection

QueueConnection

TopicConnection

Destination

Queue

Topic

Session

QueueSession

TopicSession

MessageProducer

QueueSender

TopicPublisher

MessageConsumer

QueueReceiver

TopicSubscriber

(1)、点对点方式(point-to-point)

点对点的消息发送方式主要建立在MessageQueue,Sender,reciever上,MessageQueue存贮消息,Sneder发送消息,receive接收消息.具体点就是SenderClient发送MessageQueue,而receiverCliernt从Queue中接收消息和"发送消息已接受"到Quere,确认消息接收。消息发送客户端与接收客户端没有时间上的依赖,发送客户端可以在任何时刻发送信息到Queue,而不需要知道接收客户端是不是在运行

(2)、发布/订阅方式(publish/subscriberMessaging)

发布/订阅方式用于多接收客户端的方式.作为发布订阅的方式,可能存在多个接收客户端,并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。作为subscriber,在接收消息时有两种方法,destination的receive方法,和实现messagelistener接口的onMessage方法。

2、ActiviteMQ接收和发送消息基本流程





发送消息的基本步骤:

(1)、创建连接使用的工厂类JMSConnectionFactory

(2)、使用管理对象JMSConnectionFactory建立连接Connection,并启动

(3)、使用连接Connection建立会话Session

(4)、使用会话Session和管理对象Destination创建消息生产者MessageSender

(5)、使用消息生产者MessageSender发送消息

消息接收者从JMS接受消息的步骤

(1)、创建连接使用的工厂类JMSConnectionFactory

(2)、使用管理对象JMSConnectionFactory建立连接Connection,并启动

(3)、使用连接Connection建立会话Session

(4)、使用会话Session和管理对象Destination创建消息接收者MessageReceiver

(5)、使用消息接收者MessageReceiver接受消息,需要用setMessageListener将MessageListener接口绑定到MessageReceiver消息接收者必须实现了MessageListener接口,需要定义onMessage事件方法。

五、代码示例

在代码开始,我们先建一个project,在这个project中添加如下jar包





添加完jar包后就可以开始实际的代码工作了。

1、使用JMS方式发送接收消息

消息发送者

packagecom.hoo.mq.jms;


importjavax.jms.Connection;

importjavax.jms.ConnectionFactory;

importjavax.jms.DeliveryMode;

importjavax.jms.Destination;

importjavax.jms.MessageProducer;

importjavax.jms.Session;

importjavax.jms.TextMessage;

importorg.apache.activemq.ActiveMQConnection;

importorg.apache.activemq.ActiveMQConnectionFactory;


/**

*<b>function:</b>消息发送者

*@authorhoojo

*@createDate2013-6-19上午11:26:43

*@fileMessageSender.java

*@packagecom.hoo.mq.jms

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassMessageSender{


//发送次数

publicstaticfinalintSEND_NUM=5;

//tcp地址

publicstaticfinalStringBROKER_URL="tcp://localhost:61616";

//目标,在ActiveMQ管理员控制台创建'target='_blank'>http://localhost:8161/admin/queues.jsp[/code]
publicstaticfinalStringDESTINATION="hoo.mq.queue";


/**

*<b>function:</b>发送消息

*@authorhoojo

*@createDate2013-6-19下午12:05:42

*@paramsession

*@paramproducer

*@throwsException

*/

publicstaticvoidsendMessage(Sessionsession,MessageProducerproducer)throwsException{

for(inti=0;i<SEND_NUM;i++){

Stringmessage="发送消息第"+(i+1)+"条";

TextMessagetext=session.createTextMessage(message);


System.out.println(message);

producer.send(text);

}

}


publicstaticvoidrun()throwsException{


Connectionconnection=null;

Sessionsession=null;

try{

//创建链接工厂

ConnectionFactoryfactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,BROKER_URL);

//通过工厂创建一个连接

connection=factory.createConnection();

//启动连接

connection.start();

//创建一个session会话

session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

//创建一个消息队列

Destinationdestination=session.createQueue(DESTINATION);

//创建消息制作者

MessageProducerproducer=session.createProducer(destination);

//设置持久化模式

producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

sendMessage(session,producer);

//提交会话

session.commit();


}catch(Exceptione){

throwe;

}finally{

//关闭释放资源

if(session!=null){

session.close();

}

if(connection!=null){

connection.close();

}

}

}


publicstaticvoidmain(String[]args)throwsException{

MessageSender.run();

}

}


接受者

packagecom.hoo.mq.jms;


importjavax.jms.Connection;

importjavax.jms.ConnectionFactory;

importjavax.jms.Destination;

importjavax.jms.Message;

importjavax.jms.MessageConsumer;

importjavax.jms.Session;

importjavax.jms.TextMessage;

importorg.apache.activemq.ActiveMQConnection;

importorg.apache.activemq.ActiveMQConnectionFactory;


/**

*<b>function:</b>消息接收者

*@authorhoojo

*@createDate2013-6-19下午01:34:27

*@fileMessageReceiver.java

*@packagecom.hoo.mq.jms

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassMessageReceiver{


//tcp地址

publicstaticfinalStringBROKER_URL="tcp://localhost:61616";

//目标,在ActiveMQ管理员控制台创建'target='_blank'>http://localhost:8161/admin/queues.jsp[/code]
publicstaticfinalStringDESTINATION="hoo.mq.queue";



publicstaticvoidrun()throwsException{


Connectionconnection=null;

Sessionsession=null;

try{

//创建链接工厂

ConnectionFactoryfactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,BROKER_URL);

//通过工厂创建一个连接

connection=factory.createConnection();

//启动连接

connection.start();

//创建一个session会话

session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

//创建一个消息队列

Destinationdestination=session.createQueue(DESTINATION);

//创建消息制作者

MessageConsumerconsumer=session.createConsumer(destination);


while(true){

//接收数据的时间(等待)100ms

Messagemessage=consumer.receive(1000*100);


TextMessagetext=(TextMessage)message;

if(text!=null){

System.out.println("接收:"+text.getText());

}else{

break;

}

}


//提交会话

session.commit();


}catch(Exceptione){

throwe;

}finally{

//关闭释放资源

if(session!=null){

session.close();

}

if(connection!=null){

connection.close();

}

}

}


publicstaticvoidmain(String[]args)throwsException{

MessageReceiver.run();

}

}


2、Queue队列方式发送点对点消息数据

发送方

packagecom.hoo.mq.queue;


importjavax.jms.DeliveryMode;

importjavax.jms.MapMessage;

importjavax.jms.Queue;

importjavax.jms.QueueConnection;

importjavax.jms.QueueConnectionFactory;

importjavax.jms.QueueSession;

importjavax.jms.Session;

importorg.apache.activemq.ActiveMQConnection;

importorg.apache.activemq.ActiveMQConnectionFactory;


/**

*<b>function:</b>Queue方式消息发送者

*@authorhoojo

*@createDate2013-6-19下午04:34:36

*@fileQueueSender.java

*@packagecom.hoo.mq.queue

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassQueueSender{


//发送次数

publicstaticfinalintSEND_NUM=5;

//tcp地址

publicstaticfinalStringBROKER_URL="tcp://localhost:61616";

//目标,在ActiveMQ管理员控制台创建'target='_blank'>http://localhost:8161/admin/queues.jsp[/code]
publicstaticfinalStringDESTINATION="hoo.mq.queue";


/**

*<b>function:</b>发送消息

*@authorhoojo

*@createDate2013-6-19下午12:05:42

*@paramsession

*@paramsender

*@throwsException

*/

publicstaticvoidsendMessage(QueueSessionsession,javax.jms.QueueSendersender)throwsException{

for(inti=0;i<SEND_NUM;i++){

Stringmessage="发送消息第"+(i+1)+"条";


MapMessagemap=session.createMapMessage();

map.setString("text",message);

map.setLong("time",System.currentTimeMillis());

System.out.println(map);


sender.send(map);

}

}


publicstaticvoidrun()throwsException{


QueueConnectionconnection=null;

QueueSessionsession=null;

try{

//创建链接工厂

QueueConnectionFactoryfactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,BROKER_URL);

//通过工厂创建一个连接

connection=factory.createQueueConnection();

//启动连接

connection.start();

//创建一个session会话

session=connection.createQueueSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

//创建一个消息队列

Queuequeue=session.createQueue(DESTINATION);

//创建消息发送者

javax.jms.QueueSendersender=session.createSender(queue);

//设置持久化模式

sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

sendMessage(session,sender);

//提交会话

session.commit();


}catch(Exceptione){

throwe;

}finally{

//关闭释放资源

if(session!=null){

session.close();

}

if(connection!=null){

connection.close();

}

}

}


publicstaticvoidmain(String[]args)throwsException{

QueueSender.run();

}

}


接收方

packagecom.hoo.mq.queue;


importjavax.jms.JMSException;

importjavax.jms.MapMessage;

importjavax.jms.Message;

importjavax.jms.MessageListener;

importjavax.jms.Queue;

importjavax.jms.QueueConnection;

importjavax.jms.QueueConnectionFactory;

importjavax.jms.QueueSession;

importjavax.jms.Session;

importorg.apache.activemq.ActiveMQConnection;

importorg.apache.activemq.ActiveMQConnectionFactory;


/**

*<b>function:</b>消息接收者;依赖hawtbuf-1.9.jar

*@authorhoojo

*@createDate2013-6-19下午01:34:27

*@fileMessageReceiver.java

*@packagecom.hoo.mq.queue

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassQueueReceiver{


//tcp地址

publicstaticfinalStringBROKER_URL="tcp://localhost:61616";

//目标,在ActiveMQ管理员控制台创建'target='_blank'>http://localhost:8161/admin/queues.jsp[/code]
publicstaticfinalStringTARGET="hoo.mq.queue";



publicstaticvoidrun()throwsException{


QueueConnectionconnection=null;

QueueSessionsession=null;

try{

//创建链接工厂

QueueConnectionFactoryfactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,BROKER_URL);

//通过工厂创建一个连接

connection=factory.createQueueConnection();

//启动连接

connection.start();

//创建一个session会话

session=connection.createQueueSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

//创建一个消息队列

Queuequeue=session.createQueue(TARGET);

//创建消息制作者

javax.jms.QueueReceiverreceiver=session.createReceiver(queue);


receiver.setMessageListener(newMessageListener(){

publicvoidonMessage(Messagemsg){

if(msg!=null){

MapMessagemap=(MapMessage)msg;

try{

System.out.println(map.getLong("time")+"接收#"+map.getString("text"));

}catch(JMSExceptione){

e.printStackTrace();

}

}

}

});

//休眠100ms再关闭

Thread.sleep(1000*100);


//提交会话

session.commit();


}catch(Exceptione){

throwe;

}finally{

//关闭释放资源

if(session!=null){

session.close();

}

if(connection!=null){

connection.close();

}

}

}


publicstaticvoidmain(String[]args)throwsException{

QueueReceiver.run();

}

}


3、Topic主题发布和订阅消息

消息发送方

packagecom.hoo.mq.topic;


importjavax.jms.DeliveryMode;

importjavax.jms.MapMessage;

importjavax.jms.Session;

importjavax.jms.Topic;

importjavax.jms.TopicConnection;

importjavax.jms.TopicConnectionFactory;

importjavax.jms.TopicPublisher;

importjavax.jms.TopicSession;

importorg.apache.activemq.ActiveMQConnection;

importorg.apache.activemq.ActiveMQConnectionFactory;



/**

*<b>function:</b>Queue方式消息发送者

*@authorhoojo

*@createDate2013-6-19下午04:34:36

*@fileQueueSender.java

*@packagecom.hoo.mq.topic

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassTopicSender{


//发送次数

publicstaticfinalintSEND_NUM=5;

//tcp地址

publicstaticfinalStringBROKER_URL="tcp://localhost:61616";

//目标,在ActiveMQ管理员控制台创建'target='_blank'>http://localhost:8161/admin/queues.jsp[/code]
publicstaticfinalStringDESTINATION="hoo.mq.topic";


/**

*<b>function:</b>发送消息

*@authorhoojo

*@createDate2013-6-19下午12:05:42

*@paramsession会话

*@parampublisher发布者

*@throwsException

*/

publicstaticvoidsendMessage(TopicSessionsession,TopicPublisherpublisher)throwsException{

for(inti=0;i<SEND_NUM;i++){

Stringmessage="发送消息第"+(i+1)+"条";


MapMessagemap=session.createMapMessage();

map.setString("text",message);

map.setLong("time",System.currentTimeMillis());

System.out.println(map);


publisher.send(map);

}

}


publicstaticvoidrun()throwsException{


TopicConnectionconnection=null;

TopicSessionsession=null;

try{

//创建链接工厂

TopicConnectionFactoryfactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,BROKER_URL);

//通过工厂创建一个连接

connection=factory.createTopicConnection();

//启动连接

connection.start();

//创建一个session会话

session=connection.createTopicSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

//创建一个消息队列

Topictopic=session.createTopic(DESTINATION);

//创建消息发送者

TopicPublisherpublisher=session.createPublisher(topic);

//设置持久化模式

publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

sendMessage(session,publisher);

//提交会话

session.commit();


}catch(Exceptione){

throwe;

}finally{

//关闭释放资源

if(session!=null){

session.close();

}

if(connection!=null){

connection.close();

}

}

}


publicstaticvoidmain(String[]args)throwsException{

TopicSender.run();

}

}


接收方

packagecom.hoo.mq.topic;


importjavax.jms.JMSException;

importjavax.jms.MapMessage;

importjavax.jms.Message;

importjavax.jms.MessageListener;

importjavax.jms.Session;

importjavax.jms.Topic;

importjavax.jms.TopicConnection;

importjavax.jms.TopicConnectionFactory;

importjavax.jms.TopicSession;

importjavax.jms.TopicSubscriber;

importorg.apache.activemq.ActiveMQConnection;

importorg.apache.activemq.ActiveMQConnectionFactory;


/**

*<b>function:</b>消息接收者;依赖hawtbuf-1.9.jar

*@authorhoojo

*@createDate2013-6-19下午01:34:27

*@fileMessageReceiver.java

*@packagecom.hoo.mq.topic

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassTopicReceiver{


//tcp地址

publicstaticfinalStringBROKER_URL="tcp://localhost:61616";

//目标,在ActiveMQ管理员控制台创建'target='_blank'>http://localhost:8161/admin/queues.jsp[/code]
publicstaticfinalStringTARGET="hoo.mq.topic";



publicstaticvoidrun()throwsException{


TopicConnectionconnection=null;

TopicSessionsession=null;

try{

//创建链接工厂

TopicConnectionFactoryfactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,BROKER_URL);

//通过工厂创建一个连接

connection=factory.createTopicConnection();

//启动连接

connection.start();

//创建一个session会话

session=connection.createTopicSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

//创建一个消息队列

Topictopic=session.createTopic(TARGET);

//创建消息制作者

TopicSubscribersubscriber=session.createSubscriber(topic);


subscriber.setMessageListener(newMessageListener(){

publicvoidonMessage(Messagemsg){

if(msg!=null){

MapMessagemap=(MapMessage)msg;

try{

System.out.println(map.getLong("time")+"接收#"+map.getString("text"));

}catch(JMSExceptione){

e.printStackTrace();

}

}

}

});

//休眠100ms再关闭

Thread.sleep(1000*100);


//提交会话

session.commit();


}catch(Exceptione){

throwe;

}finally{

//关闭释放资源

if(session!=null){

session.close();

}

if(connection!=null){

connection.close();

}

}

}


publicstaticvoidmain(String[]args)throwsException{

TopicReceiver.run();

}

}


4、整合Spring实现消息发送和接收,在整合之前我们需要添加jar包,需要的jar包如下





这些jar包可以在D:\apache-activemq-5.8.0\lib这个lib目录中找到,添加完jar包后就开始编码工作。

消息发送者

packagecom.hoo.mq.spring.support;


importjava.util.Date;

importjavax.jms.JMSException;

importjavax.jms.MapMessage;

importjavax.jms.Message;

importjavax.jms.Session;

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.FileSystemXmlApplicationContext;

importorg.springframework.jms.core.JmsTemplate;

importorg.springframework.jms.core.MessageCreator;


/**

*<b>function:</b>SpringJMSTemplate消息发送者

*@authorhoojo

*@createDate2013-6-24下午02:18:48

*@fileSender.java

*@packagecom.hoo.mq.spring.support

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassSender{


publicstaticvoidmain(String[]args){

ApplicationContextctx=newFileSystemXmlApplicationContext("classpath:applicationContext-*.xml");

JmsTemplatejmsTemplate=(JmsTemplate)ctx.getBean("jmsTemplate");


jmsTemplate.send(newMessageCreator(){

publicMessagecreateMessage(Sessionsession)throwsJMSException{

MapMessagemessage=session.createMapMessage();

message.setString("message","currentsystemtime:"+newDate().getTime());


returnmessage;

}

});

}

}


消息接收者

packagecom.hoo.mq.spring.support;


importjava.util.Map;

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.FileSystemXmlApplicationContext;

importorg.springframework.jms.core.JmsTemplate;


/**

*<b>function:</b>SpringJMSTemplate消息接收者

*@authorhoojo

*@createDate2013-6-24下午02:22:32

*@fileReceiver.java

*@packagecom.hoo.mq.spring.support

*@projectActiveMQ-5.8

*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo[/code]
*@emailhoojo_@126.com

*@version1.0

*/

publicclassReceiver{


@SuppressWarnings("unchecked")

publicstaticvoidmain(String[]args){

ApplicationContextctx=newFileSystemXmlApplicationContext("classpath:applicationContext-*.xml");


JmsTemplatejmsTemplate=(JmsTemplate)ctx.getBean("jmsTemplate");

while(true){

Map<String,Object>map=(Map<String,Object>)jmsTemplate.receiveAndConvert();


System.out.println("收到消息:"+map.get("message"));

}

}

}


这里主要是用到了JmsTemplate这个消息模板,这个对象在spring的IoC容器中管理,所以要从spring的容器上下文中获取。下面看看spring的配置文件applicationContext-beans.xml内容:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

'target='_blank'>http://www.springframework.org/schema/beans/spring-beans-3.1.xsd[/code]
'target='_blank'>http://www.springframework.org/schema/context[/code]
'target='_blank'>http://www.springframework.org/schema/context/spring-context-3.1.xsd">[/code]

<!--连接池-->

<beanid="pooledConnectionFactory"class="org.apache.activemq.pool.PooledConnectionFactory"destroy-method="stop">

<propertyname="connectionFactory">

<beanclass="org.apache.activemq.ActiveMQConnectionFactory">

<propertyname="brokerURL"value="tcp://localhost:61616"/>

</bean>

</property>

</bean>


<!--连接工厂-->

<beanid="activeMQConnectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory">

<propertyname="brokerURL"value="tcp://localhost:61616"/>

</bean>


<!--配置消息目标-->

<beanid="destination"class="org.apache.activemq.command.ActiveMQQueue">

<!--目标,在ActiveMQ管理员控制台创建http://localhost:8161/admin/queues.jsp-->

<constructor-argindex="0"value="hoo.mq.queue"/>

</bean>


<!--消息模板-->

<beanid="jmsTemplate"class="org.springframework.jms.core.JmsTemplate">

<propertyname="connectionFactory"ref="activeMQConnectionFactory"/>

<propertyname="defaultDestination"ref="destination"/>

<propertyname="messageConverter">

<beanclass="org.springframework.jms.support.converter.SimpleMessageConverter"/>

</property>

</bean>

</beans>


这里的整合就比较简单了,如果你是web工程,那你在需要用jms的时候,只需用注入jmsTemplate即可。


1、下载安装ActiveMQ

  ActiveMQ官网下载地址:http://activemq.apache.org/download.html

  ActiveMQ提供了Windows和Linux、Unix等几个版本,楼主这里选择了Linux版本下进行开发。



  下载完安装包,解压之后的目录:



 

  从它的目录来说,还是很简单的:

bin存放的是脚本文件
conf存放的是基本配置文件
data存放的是日志文件
docs存放的是说明文档
examples存放的是简单的实例
lib存放的是activemq所需jar包
webapps用于存放项目的目录


2、启动ActiveMQ 

  进入到ActiveMQ安装目录的Bin目录,linux下输入./activemqstart启动activeMQ服务。

  输入命令之后,会提示我们创建了一个进程IP号,这时候说明服务已经成功启动了。


  

  ActiveMQ默认启动时,启动了内置的jetty服务器,提供一个用于监控ActiveMQ的admin应用。

  admin:http://127.0.0.1:8161/admin/

  我们在浏览器打开链接之后输入账号密码(这里和tomcat服务器类似)

  默认账号:admin

  密码:admin

  


   到这里为止,ActiveMQ服务端就启动完毕了。

   ActiveMQ在linux下的终止命令是./activemqstop


3、创建一个ActiveMQ工程

  项目目录结构:

  


  上述在官网下载ActiveMq的时候,我们可以在目录下看到一个jar包:

  


  这个jar包就是我们需要在项目中进行开发中使用到的相关依赖。


  3.1创建生产者

publicclassProducter{

//ActiveMq的默认用户名
privatestaticfinalStringUSERNAME=ActiveMQConnection.DEFAULT_USER;
//ActiveMq的默认登录密码
privatestaticfinalStringPASSWORD=ActiveMQConnection.DEFAULT_PASSWORD;
//ActiveMQ的链接地址
privatestaticfinalStringBROKEN_URL=ActiveMQConnection.DEFAULT_BROKER_URL;

AtomicIntegercount=newAtomicInteger(0);
//链接工厂
ConnectionFactoryconnectionFactory;
//链接对象
Connectionconnection;
//事务管理
Sessionsession;
ThreadLocal<MessageProducer>threadLocal=newThreadLocal<>();

publicvoidinit(){
try{
//创建一个链接工厂
connectionFactory=newActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
//从工厂中创建一个链接
connection=connectionFactory.createConnection();
//开启链接
connection.start();
//创建一个事务(这里通过参数可以设置事务的级别)
session=connection.createSession(true,Session.SESSION_TRANSACTED);
}catch(JMSExceptione){
e.printStackTrace();
}
}

publicvoidsendMessage(Stringdisname){
try{
//创建一个消息队列
Queuequeue=session.createQueue(disname);
//消息生产者
MessageProducermessageProducer=null;
if(threadLocal.get()!=null){
messageProducer=threadLocal.get();
}else{
messageProducer=session.createProducer(queue);
threadLocal.set(messageProducer);
}
while(true){
Thread.sleep(1000);
intnum=count.getAndIncrement();
//创建一条消息
TextMessagemsg=session.createTextMessage(Thread.currentThread().getName()+
"productor:我是大帅哥,我现在正在生产东西!,count:"+num);
System.out.println(Thread.currentThread().getName()+
"productor:我是大帅哥,我现在正在生产东西!,count:"+num);
//发送消息
messageProducer.send(msg);
//提交事务
session.commit();
}
}catch(JMSExceptione){
e.printStackTrace();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}


    


  3.2创建消费者

publicclassComsumer{

privatestaticfinalStringUSERNAME=ActiveMQConnection.DEFAULT_USER;

privatestaticfinalStringPASSWORD=ActiveMQConnection.DEFAULT_PASSWORD;

privatestaticfinalStringBROKEN_URL=ActiveMQConnection.DEFAULT_BROKER_URL;

ConnectionFactoryconnectionFactory;

Connectionconnection;

Sessionsession;

ThreadLocal<MessageConsumer>threadLocal=newThreadLocal<>();
AtomicIntegercount=newAtomicInteger();

publicvoidinit(){
try{
connectionFactory=newActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
connection=connectionFactory.createConnection();
connection.start();
session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
}catch(JMSExceptione){
e.printStackTrace();
}
}

publicvoidgetMessage(Stringdisname){
try{
Queuequeue=session.createQueue(disname);
MessageConsumerconsumer=null;

if(threadLocal.get()!=null){
consumer=threadLocal.get();
}else{
consumer=session.createConsumer(queue);
threadLocal.set(consumer);
}
while(true){
Thread.sleep(1000);
TextMessagemsg=(TextMessage)consumer.receive();
if(msg!=null){
msg.acknowledge();
System.out.println(Thread.currentThread().getName()+":Consumer:我是消费者,我正在消费Msg"+msg.getText()+"--->"+count.getAndIncrement());
}else{
break;
}
}
}catch(JMSExceptione){
e.printStackTrace();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}



4、运行ActiveMQ项目


  4.1生产者开始生产消息

publicclassTestMq{
publicstaticvoidmain(String[]args){
Producterproducter=newProducter();
producter.init();
TestMqtestMq=newTestMq();
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
//Thread1
newThread(testMq.newProductorMq(producter)).start();
//Thread2
newThread(testMq.newProductorMq(producter)).start();
//Thread3
newThread(testMq.newProductorMq(producter)).start();
//Thread4
newThread(testMq.newProductorMq(producter)).start();
//Thread5
newThread(testMq.newProductorMq(producter)).start();
}

privateclassProductorMqimplementsRunnable{
Producterproducter;
publicProductorMq(Producterproducter){
this.producter=producter;
}

@Override
publicvoidrun(){
while(true){
try{
producter.sendMessage("Jaycekon-MQ");
Thread.sleep(10000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
}


   运行结果:

INFO|Successfullyconnectedtotcp://localhost:61616
Thread-6productor:我是大帅哥,我现在正在生产东西!,count:0
Thread-4productor:我是大帅哥,我现在正在生产东西!,count:1
Thread-2productor:我是大帅哥,我现在正在生产东西!,count:3
Thread-5productor:我是大帅哥,我现在正在生产东西!,count:2
Thread-3productor:我是大帅哥,我现在正在生产东西!,count:4
Thread-6productor:我是大帅哥,我现在正在生产东西!,count:5
Thread-3productor:我是大帅哥,我现在正在生产东西!,count:6
Thread-5productor:我是大帅哥,我现在正在生产东西!,count:7
Thread-2productor:我是大帅哥,我现在正在生产东西!,count:8
Thread-4productor:我是大帅哥,我现在正在生产东西!,count:9
Thread-6productor:我是大帅哥,我现在正在生产东西!,count:10
Thread-3productor:我是大帅哥,我现在正在生产东西!,count:11
Thread-5productor:我是大帅哥,我现在正在生产东西!,count:12
Thread-2productor:我是大帅哥,我现在正在生产东西!,count:13
Thread-4productor:我是大帅哥,我现在正在生产东西!,count:14
Thread-6productor:我是大帅哥,我现在正在生产东西!,count:15
Thread-3productor:我是大帅哥,我现在正在生产东西!,count:16
Thread-5productor:我是大帅哥,我现在正在生产东西!,count:17
Thread-2productor:我是大帅哥,我现在正在生产东西!,count:18
Thread-4productor:我是大帅哥,我现在正在生产东西!,count:19


  



  4.2消费者开始消费消息

publicclassTestConsumer{
publicstaticvoidmain(String[]args){
Comsumercomsumer=newComsumer();
comsumer.init();
TestConsumertestConsumer=newTestConsumer();
newThread(testConsumer.newConsumerMq(comsumer)).start();
newThread(testConsumer.newConsumerMq(comsumer)).start();
newThread(testConsumer.newConsumerMq(comsumer)).start();
newThread(testConsumer.newConsumerMq(comsumer)).start();
}

privateclassConsumerMqimplementsRunnable{
Comsumercomsumer;
publicConsumerMq(Comsumercomsumer){
this.comsumer=comsumer;
}

@Override
publicvoidrun(){
while(true){
try{
comsumer.getMessage("Jaycekon-MQ");
Thread.sleep(10000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
}


  运行结果:

  

  查看运行结果,我们可以做ActiveMQ服务端:http://127.0.0.1:8161/admin/里面的Queues中查看我们生产的消息。




5、ActiveMQ的特性


 5.1ActiveMq的特性 

多种语言和协议编写客户端。语言:Java,C,C++,C#,Ruby,Perl,Python,PHP。应用协议:OpenWire,StompREST,WSNotification,XMPP,AMQP
完全支持JMS1.1和J2EE1.4规范(持久化,XA消息,事务)
对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性
通过了常见J2EE服务器(如Geronimo,JBoss4,GlassFish,WebLogic)的测试,其中通过JCA1.5resourceadaptors的配置,可以让ActiveMQ可以自动的部署到任何兼容J2EE
1.4商业服务器上
支持多种传送协议:in-VM,TCP,SSL,NIO,UDP,JGroups,JXTA
支持通过JDBC和journal提供高速的消息持久化
从设计上保证了高性能的集群,客户端-服务器,点对点
支持Ajax
支持与Axis的整合
可以很容易得调用内嵌JMSprovider,进行测试


 


 5.2什么情况下使用ActiveMQ?

多个项目之间集成

(1)跨平台

(2)多语言

(3)多项目
降低系统间模块的耦合度,解耦

(1)软件扩展性
系统前后端隔离

(1)前后端隔离,屏蔽高安全区
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: