active mq使用 http://www.huaishao8.com/tag/activemq kagula 2011-9-6 介绍 active mq是个消息队列管理器,用于通讯的中间件。 java active mq的常见使用方式有两种:[1]点对点方式(producer/consumer)[2]发布/订阅者方式(publisher/subscriber model)
active mq使用http://www.huaishao8.com/tag/activemq
kagula
2011-9-6
介绍 active mq是个消息队列管理器,用于通讯的中间件。
java + active mq的常见使用方式有两种:[1]点对点方式(producer/consumer)[2]发布/订阅者方式(publisher/subscriber model)
测试环境[1]jdk1.6.x [2]eclipse indigo [3]active mq 5.4.2
建议不要使用active mq 5.5.0 因为activemq-all-5.5.0.jar缺少依赖项。
正文参考资料[1] 保证active mq已经正确安装与启动。
点对点(producer、consumer)模式
图一 jms对象模型
producer端源码示例
import org.apache.activemq.activemqconnection; import org.apache.activemq.activemqconnectionfactory; import javax.jms.*; /** * 消息的生产者(发送者) * */ public class jmssender { public static void main(string[] args) throws jmsexception { // connectionfactory :连接工厂,jms 用它创建连接 connectionfactory connectionfactory = new activemqconnectionfactory( activemqconnection.default_user, activemqconnection.default_password, failover://(tcp://127.0.0.1:61616)); //jms 客户端到jms provider 的连接 connection connection = connectionfactory.createconnection(); connection.start(); // session: 一个发送或接收消息的线程 // createsession的第一个参数boolean.false指的是当前session不是一个事务 // 即消息是自动提交,你不能调用session.commit函数提交事务。 // createsession的第一个参数boolean.true指的是新创建的session是一个事务 // 你必须调用session.commit函数来提交事务,才能真正把消息放到队列服务器中 session session = connection.createsession(boolean.true, session.auto_acknowledge); // destination :消息的目的地;消息发送给谁. // 获取session注意参数值my-queue是query的名字 destination destination = session.createqueue(my-queue); // messageproducer:消息生产者 messageproducer producer = session.createproducer(destination); //设置不持久化 producer.setdeliverymode(deliverymode.non_persistent); //发送一条消息 sendmsg(session, producer); connection.close(); } /** * 在指定的会话上,通过指定的消息生产者发出一条消息 * * @param session 消息会话 * @param producer 消息生产者 */ public static void sendmsg(session session, messageproducer producer) throws jmsexception { //创建一条文本消息 textmessage message = session.createtextmessage(hello activemq!); //通过消息生产者发出消息 producer.send(message); system.out.println(); } }
consumer端源码示例
import org.apache.activemq.activemqconnection; import org.apache.activemq.activemqconnectionfactory; import javax.jms.*; public class jmsreceiver { public static void main(string[] args) throws jmsexception { // connectionfactory :连接工厂,jms 用它创建连接 connectionfactory connectionfactory = new activemqconnectionfactory( activemqconnection.default_user, activemqconnection.default_password, tcp://127.0.0.1:61616); //jms 客户端到jms provider 的连接 connection connection = connectionfactory.createconnection(); connection.start(); // session: 一个发送或接收消息的线程 // createsession的第一个参数boolean.false指的是当前session不是一个事务 // 即消息是自动提交或接收,你不能调用session.commit函数提交事务。 // createsession的第一个参数boolean.true指的是新创建的session是一个事务 // 你必须调用session.commit函数来提交事务,否则接收过的消息还在 // 队列服务器中,你再接收一次,发现他们还待着。 session session = connection.createsession(boolean.true, session.auto_acknowledge); // destination :消息的目的地;消息从哪个队列接收. destination destination = session.createqueue(my-queue); // 消费者,消息接收者 messageconsumer consumer = session.createconsumer(destination); while (true) { //1秒内没有收到消息,即返回 textmessage message = (textmessage) consumer.receive(1000); if (null != message) system.out.println(收到消息: + message.gettext()); else break; } session.commit(); session.close(); connection.close(); } }
publisher/subscriber model消息传播以一对多的关系传递,即一个publisher,多个subscriber。
你也可以为下面的源码示例加入下面的代码
topicpublisher.setdeliverymode(deliverymode.persistent);
它的作用是:activemq服务器重启后,仍保留你发上去的消息。
你也可以通过下面的代码段,设置发上去的消息在mq服务器上的存活时间
topicpublisher.settimetolive(1000*60*60*24*3);//ms为单位
源码示例
public class sampleutilities { static public class donelatch { boolean done = false; /** * waits until done is set to true. */ public void waittilldone() { synchronized (this) { while (! done) { try { this.wait(); } catch (interruptedexception ie) {} } } } /** * sets done to true. */ public void alldone() { synchronized (this) { done = true; this.notify(); } } }}
import java.util.date;import javax.jms.*;import org.apache.activemq.activemqconnection;import org.apache.activemq.activemqconnectionfactory;/** * @author kim haase * @comment&modified by kagula * @version 1.6, 08/18/00 * @lastupdatedate 09/06/11 */public class asynchtopicexample { final string control_queue = controlqueue; string topicname = null; int exitresult = 0; public static connectionfactory getjmsconnectionfactory() throws jmsexception { string user = activemqconnection.default_user; string password = activemqconnection.default_password; string url = activemqconnection.default_broker_url; return new activemqconnectionfactory(user, password, url); } public class asynchsubscriber extends thread { private class textlistener implements messagelistener { final sampleutilities.donelatch monitor = new sampleutilities.donelatch(); //若收到消息onmessage被调用(实现了messagelistener代理) public void onmessage(message message) { if (message instanceof textmessage) { textmessage msg = (textmessage) message; try { system.out.println(订阅者线程:读取消息: + msg.gettext()); } catch (jmsexception e) { system.out.println(exception in onmessage(): + e.tostring()); } } else { //收到非textmessage类型的消息,publisher指示你可以结束订阅 monitor.alldone(); } } }//结束textlistener class的定义 /** * runs the thread. */ public void run() { connectionfactory topicconnectionfactory = null; connection topicconnection = null; session topicsession = null; topic topic = null; messageconsumer topicsubscriber = null; textlistener topiclistener = null; try { topicconnectionfactory = asynchtopicexample.getjmsconnectionfactory(); topicconnection = topicconnectionfactory.createconnection(); topicsession = topicconnection.createsession(false, session.auto_acknowledge); topic = topicsession.createtopic(topicname); } catch (exception e) { system.out.println(connection problem: + e.tostring()); if (topicconnection != null) { try { topicconnection.close(); } catch (jmsexception ee) {} } system.exit(1); } try { topicsubscriber = topicsession.createconsumer(topic); topiclistener = new textlistener(); topicsubscriber.setmessagelistener(topiclistener); topicconnection.start(); /* * asynchronously process messages. * block until publisher issues a control message indicating * end of publish stream. */ topiclistener.monitor.waittilldone(); } catch (jmsexception e) { system.out.println(exception occurred: + e.tostring()); exitresult = 1; } finally { if (topicconnection != null) { try { topicconnection.close(); } catch (jmsexception e) { exitresult = 1; } } } } } /** * the multiplepublisher class publishes several message to a topic. * * @author kim haase * @version 1.6, 08/18/00 */ public class multiplepublisher extends thread { /** * runs the thread. */ public void run() { connectionfactory topicconnectionfactory = null; connection topicconnection = null; session topicsession = null; topic topic = null; messageproducer topicpublisher = null; textmessage message = null; final int nummsgs = 20; final string msg_text = new string(here is a message); try { topicconnectionfactory = asynchtopicexample.getjmsconnectionfactory(); topicconnection = topicconnectionfactory.createconnection(); topicsession = topicconnection.createsession(false,session.auto_acknowledge); topic = topicsession.createtopic(topicname); } catch (exception e) { system.out.println(connection problem: + e.tostring()); if (topicconnection != null) { try { topicconnection.close(); } catch (jmsexception ee) {} } system.exit(1); } try { topicpublisher = topicsession.createproducer(topic); message = topicsession.createtextmessage(); for (int i = 0; i
参考资料[1]《active mq入门(转) 》
http://yeweiyun868.blog.163.com/blog/static/563784432010112301916556/
[2]《eclipse中添加src和javadoc的方法》
http://hi.baidu.com/rebeccacao/blog/item/d3f67ed3af8384229b5027bf.html
[3]active mq 官网
http://activemq.apache.org/
[4]《java message service specification》含jms1.1标准示例代码
http://www.oracle.com/technetwork/java/docs-136352.html
[5]《jms example: publish and subscribe》
http://jmsexample.zcage.com/index2.html
=========================================================
active mq c#实现active mq c#实现kagula
2011/9/24
内容概要主要以源码的形式介绍如何用c#实现同active mq 的通讯。本文假设你已经正确安装jdk1.6.x,了解active mq并有一定的编程基础。
正文 jms 程序的最终目的是生产和消费的消息能被其他程序使用,jms 的 message 是一个既简单又不乏灵活性的基本格式,允许创建不同平台上符合非jms 程序格式的消息。
message 由消息头,属性和消息体三部份组成。
active mq支持过滤机制,即生产者可以设置消息的属性(properties),该属性与消费者端的selector对应,只有消费者设置的selector与消息的properties匹配,消息才会发给该消费者。topic和queue都支持selector。
示例代码
using system;using system.collections.generic;using system.linq;using system.text;using system.windows;using system.windows.controls;using system.windows.data;using system.windows.documents;using system.windows.input;using system.windows.media;using system.windows.media.imaging;using system.windows.navigation;using system.windows.shapes;using apache.nms;using system.diagnostics;using apache.nms.util;using system.windows.threading;/* * 功能描述:c#使用activemq示例 * 修改次数:2 * 最后更新: by kagula,2012-07-31 * * 前提条件: * [1]apache-activemq-5.4.2 * [2]apache.nms.activemq-1.5.6-bin * [3]winxp sp3 * [4]vs2008 sp1 * [5]wpf工程 with .net framework 3.5 * * 启动 * * 不带安全控制方式启动 * [你的解压路径]\apache-activemq-5.4.2\bin\activemq.bat * * 安全方式启动 * 添加环境变量: activemq_encryption_password=activemq * [你的解压路径]\apache-activemq-5.4.2\bin>activemq xbean:file:../conf/activemq-security.xml * * active mq 管理地址 * http://127.0.0.1:8161/admin/ * 添加访问http://127.0.0.1:8161/admin/的限制 * * 第一步:添加访问限制 * 修改d:\apache\apache-activemq-5.4.2\conf\jetty.xml文件 * 下面这行编码,原 * * 修改为 * * * 第二步:修改登录用户名密码,缺省分别为admin,admin * d:\apache\apache-activemq-5.4.2\conf\jetty-realm.properties * * 用户管理(前提:以安全方式启动activemq) * * 在[你的解压路径]\apache-activemq-5.4.2\conf\credentials.properties文件中修改默认的用户名密码 * 在[你的解压路径]\apache-activemq-5.4.2\conf\activemq-security.xml文件中可以添加新的用户名 * e.g. 添加oa用户,密码同用户名。 * * * 在[你的解压路径]\apache-activemq-5.4.2\conf\activemq-security.xml文件中你还可以设置指定的topic或queue * 只能被哪些用户组read 或 write。 * * * 配置c# with wpf项目 * 项目的[application]->[targetframework]属性设置为[.netframework 3.5](这是vs2008wpf工程的默认设置) * 添加[你的解压路径]\apache.nms.activemq-1.5.6-bin\lib\apache.nms\net-3.5\apache.nms.dll的引用 * apache.nms.dll相当于接口 * * 如果是以debug方式调试 * 把[你的解压路径]\apache.nms.activemq-1.5.6-bin\build\net-3.5\debug\目录下的 * apache.nms.activemq.dll文件复制到你项目的debug目录下 * apache.nms.activemq.dll相当于实现 * * 如果是以release方式调试 * 参考上文,去取apache.nms,release目录下相应的dll文件,并复制到你项目的release目录下。 * * * 参考资料 * [1]《c#调用activemq官方示例》 http://activemq.apache.org/nms/examples.html * [2]《activemq nms下载地址》http://activemq.apache.org/nms/activemq-downloads.html * [3]《active mq在c#中的应用》http://www.cnblogs.com/guthing/archive/2010/06/17/1759333.html * [4]《nms api reference》http://activemq.apache.org/nms/nms-api.html */namespace testactivemqsubscriber{ /// /// interaction logic for window1.xaml /// public partial class window1 : window { private static iconnectionfactory connfac; private static iconnection connection; private static isession session; private static idestination destination; private static imessageproducer producer; private static imessageconsumer consumer; protected static itextmessage message = null; public window1() { initializecomponent(); initamq(myfirsttopic); } private void initamq(string strtopicname) { try { connfac = new nmsconnectionfactory(new uri(activemq:failover:(tcp://localhost:61616))); //新建连接 //connection = connfac.createconnection(oa,oa);//设置连接要用的用户名、密码 //如果你要持久“订阅”,则需要设置clientid,这样程序运行当中被停止,恢复运行时,能拿到没接收到的消息! connection.clientid = testing listener; connection = connfac.createconnection();//如果你是缺省方式启动active mq服务,则不需填用户名、密码 //创建session session = connection.createsession(); //发布/订阅模式,适合一对多的情况 destination = sessionutil.getdestination(session, topic:// + strtopicname); //新建生产者对象 producer = session.createproducer(destination); producer.deliverymode = msgdeliverymode.nonpersistent;//activemq服务器停止工作后,消息不再保留 //新建消费者对象:普通“订阅”模式 //consumer = session.createconsumer(destination);//不需要持久“订阅” //新建消费者对象:持久订阅模式: // 持久“订阅”后,如果你的程序被停止工作后,恢复运行, //从第一次持久订阅开始,没收到的消息还可以继续收 consumer = session.createdurableconsumer( session.gettopic(strtopicname) , connection.clientid, null, false); //设置消息接收事件 consumer.listener += new messagelistener(onmessage); //启动来自active mq的消息侦听 connection.start(); } catch (exception e) { //初始化activemq连接失败,往vs2008的output窗口写入出错信息! debug.writeline(e.message); } } private void sendmsg2topic_click(object sender, routedeventargs e) { //发送消息 itextmessage request = session.createtextmessage(datetime.now.tolocaltime()+ +tbmsg.text); producer.send(request); } protected void onmessage(imessage receivedmsg) { //接收消息 message = receivedmsg as itextmessage; //ui线程,显示收到的消息 dispatcher.invoke(dispatcherpriority.normal, new action(() => { datetime dt = new datetime(); listboxitem lbi = new listboxitem(); lbi.content = datetime.now.tolocaltime() + + message.text; lbr.items.add(lbi); })); } }}
===================================================================
active mq c++实现通讯kagula
2011-9-13
简介在参考资料[2]的基础上介绍如何用c++调用active mq的客户端api。
环境:[1]windows xp sp3
[2]visual studio 2008 sp1
阅读前提:[1]熟悉microsoft visual studio下的c++编程
[2]熟悉《active mq使用》这篇文章中的内容,即参考资料[2]
正文cms (stands for c++ messaging service)类似于jms api用于同message brokers通讯(例如active mq)。
active mq-cpp是客户端库。通过参考资料[3]下载“active mq-cpp v3.4.0 (activemq-cpp-library-3.4.0-src.zip)”
准备开发环境apr(apache portable run-time libraries,apache可移植运行库)的目的如其名称一样,主要为上层的应用程序提供一个可以跨越多操作系统平台使用的底层支持接口库。
你必须从参考[4]中下载apr-iconv包、apr-util包、apr包等三个包,并解压缩到
c:\work\apr\
c:\work\apr-iconv\
c:\work\apr-util\
等以上三个目录(必须是在上面的路径中,否则vs2008中会找不到工程依赖文件和依赖函数实现)
第一步:apr-iconv包的配置
下载http://apache.osuosl.org/apr/apr-iconv-1.2.1-win32-src-r2.zip
解压后打开包内的apriconv.dsp文件编译出release版本的apriconv-1.lib文件。
配置vs2008的头文件搜索路径为
c:\work\apr-iconv\include
配置vs2008的库文件搜索路径为
c:\work\apr-iconv\\libr
第二步:apr-util包的配置
参考资料[4]下载apr-util-1.3.12-win32-src.zip 包中的源码,编译aprutil工作空间中的aprutil项目,生成aprutil-1.lib、libaprutil-1.lib。
把“c:\work\apr-util\include”目录配置到vs2008头文件搜索路径里
把“c:\work\apr-util\libr”目录配置到vs2008库文件搜索路径里
把“c:\work\apr-util\release”目录配置到vs2008库文件搜索路径里
第三步:apr基本包的配置
参考资料[4]下载、编译apr-1.4.5-win32-src.zip 包中的源码。
编译好后在libr目录里生成apr-1.lib库、libapr-1.lib。否则activemq-cpp的acitvemq-cpp-example项目编译时会找不到库文件。
把“c:\work\apr\include”目录配置到vs2008头文件搜索路径里
把“c:\work\apr\libr”目录配置到vs2008库文件搜索路径里
把“c:\work\apr\release”目录配置到vs2008库文件搜索路径里
第四步:cppunit包的配置
在下面网址下载
http://sourceforge.net/projects/cppunit/files/cppunit/1.12.1/cppunit-1.12.1.tar.gz/download
解压缩cppunit-1.12.1.tar.gz包,并以release方式编译
把“d:\cppunit-1.12.1\include” 目录配置到vs2008头文件搜索路径里
把“d:\cppunit-1.12.1\lib”目录配置到vs2008库文件搜索路径里
其中上面的d:\是我的解压路径,你也可以是其它路径。
第五步:activemq-cpp-library-3.4.0包的配置
解包activemq-cpp-library-3.3.0-src.zip文件(从参考资料[3]中下载),并以release方式编译,如果前面几步正确,这一步不会产生任何错误。
这个zip包里,含activemq-cpp-example项目,里面有个c++源码示例,我这里的源码片段就是参考那里的。
把“d:\activemq-cpp-library-3.4.0\src\main” 目录配置到vs2008头文件搜索路径里
把“d:\activemq-cpp-library-3.4.0\src\main\decaf\internal” 目录配置到vs2008头文件搜索路径里
把“d:\activemq-cpp-library-3.4.0\vs2008-build\win32\release”目录配置到vs2008库文件搜索路径里
其中上面的d:\是我的解压路径,你也可以是其它路径。
使用“activemq-cpp”提供的api只要配置其头文件存放路径就可以了。
c++样例要运行样例文件,请确保以releasedll和debugdll方式编译成功以上各个依赖包。以debug方式调试你的应用程序时必须使用activemq-cppd.lib库文件及其对应的activemq-cppd.dll动态链接库文件,否则创建connectionfactory对象会出错。
依赖库列表(含路径,四个动态链接库,三个静态库,不包括ws2_32.lib)
d:\activemq-cpp-library-3.4.0\vs2008-build\win32\debugdll\activemq-cppd.lib
d:\activemq-cpp-library-3.4.0\vs2008-build\win32\debugdll\activemq-cppd.dll
c:\work\apr\release\libapr-1.lib
c:\work\apr\release\libapr-1.dll
c:\work\apr-util\release \libaprutil-1.dll
c:\work\apr-util\release \libaprutil-1.lib
c:\work\apr-iconv\release\ libapriconv-1.dll
新建win32 console项目在vs2008里,修改[configuration properties]->[linker]->[input]->[additional dependencies]属性为
ws2_32.lib activemq-cppd.lib libapr-1.lib libaprutil-1.lib
把需要的动态链接库文件复制到当前项目的运行目录中。
以debug方式运行成功后,http://127.0.0.1:8161/admin/queues.jsp
你会发现多个了“frommycplusplus”队列,里面已经存放了刚才发送的消息。
下面是我的完整源码testactivemq.cpp文件
// testactivemq.cpp : defines the entry point for the console application.//#include stdafx.h#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace activemq::core;using namespace decaf::util::concurrent;using namespace decaf::util;using namespace decaf::lang;using namespace cms;using namespace std;int _tmain(int argc, _tchar* argv[]){ activemq::library::activemqcpp::initializelibrary(); connection* connection; session* session; destination* destination; messageproducer* producer; std::string brokeruri(failover:(tcp://localhost:61616)); try { // create a connectionfactory auto_ptr connectionfactory( connectionfactory::createcmsconnectionfactory( brokeruri ) ); // create a connection connection = connectionfactory->createconnection(); connection->start(); // create a session session = connection->createsession( session::auto_acknowledge ); // create the destination (topic or queue) destination = session->createqueue( frommycplusplus ); // create a messageproducer from the session to the topic or queue producer = session->createproducer( destination ); producer->setdeliverymode( deliverymode::non_persistent ); // create a messages string text(hello world from c++); for( int ix=0; ixcreatetextmessage( text ); message->setintproperty( integer, ix ); producer->send( message ); delete message; } }catch ( cmsexception& e ) { e.printstacktrace(); } //释放资源 try{ if( destination != null ) delete destination; }catch ( cmsexception& e ) { e.printstacktrace(); } destination = null; try{ if( producer != null ) delete producer; }catch ( cmsexception& e ) { e.printstacktrace(); } producer = null; // close open resources. try{ if( session != null ) session->close(); if( connection != null ) connection->close(); }catch ( cmsexception& e ) { e.printstacktrace(); } try{ if( session != null ) delete session; }catch ( cmsexception& e ) { e.printstacktrace(); } session = null; try{ if( connection != null ) delete connection; }catch ( cmsexception& e ) { e.printstacktrace(); } connection = null; activemq::library::activemqcpp::shutdownlibrary(); return 0;}
参考资料[1]《解决active mq中,java与c++交互中文乱码问题》
http://www.blogjava.net/javagrass/archive/2011/05/06/349660.html
[2]《active mq使用》
http://blog.csdn.net/lee353086/article/details/6753858
[3]《active mq cms》
http://activemq.apache.org/cms/
[4]apache portable runtime project
http://apr.apache.org/
编译activemq-cpp-example碰到的问题kagula
2012-3-2
环境
[1]win7sp1
[2]apr-1.4.6-win32-src.zip
[3]apr-util-1.4.1-win32-src.zip
[4]apr-iconv-1.2.1-win32-src-r2.zip
[5]activemq-cpp-library-3.4.1-src.zip
[6]apache-activemq-5.4.3-bin.zip
[7]vs2010sp1
打开apache-activemq包里自带的activemq-cpp-example的项目虽然编译成功
但是一运行提示找不到libparutil-1.dll。
进入c:\work\aprutil编译aprutil,静态库能生成,但是动态库无法生成。
察看apr官方文档,我们知道如果在link的依赖项里设置libxxx.lib,则程序运
行的时候,会到当前运行目录里寻找相应的xxx.dll文件。
动态不成,我们用静态,把link依赖项的libapr-1.lib、libaprutil-1.lib
分别改为apr-1.lib和aprutil-1.lib,但是编译会有很多符号(函数)找不到实现。
我们替这些符号找到实现所在的lib文件,然后,补上去。
完成后的,[linker]->[input]->[additional dependencies]项内容如下
“ws2_32.lib apr-1.lib aprutil-1.lib apriconv-1.lib mswsock.lib
rpcrt4.lib”共六个库文件。
现在activemq-cpp-example程序编译成功。一运行停留在命令行下,这时启动
activemq,程序会正常往下运行并结束。问题解决。
但是如果你在c++端发送中文信息给java端,java端会报utf-8解析出错,这时
你只需要传送中文前把gbk转成utf-8再发给java端就可以了。
active mq javaclient实现
package com.test.mq.activemq;
import javax.jms.connection;
import javax.jms.deliverymode;
import javax.jms.destination;
import javax.jms.exceptionlistener;
import javax.jms.jmsexception;
import javax.jms.message;
import javax.jms.messageconsumer;
import javax.jms.messageproducer;
import javax.jms.session;
import javax.jms.textmessage;
import org.apache.activemq.activemqconnectionfactory;
/**
* hello world!
*/
public class app {
public static void main(string[] args) throws exception {
thread(new helloworldproducer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread.sleep(1000);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread.sleep(1000);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldproducer(), false);
thread.sleep(1000);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldconsumer(), false);
thread(new helloworldproducer(), false);
}
public static void thread(runnable runnable, boolean daemon) {
thread brokerthread = new thread(runnable);
brokerthread.setdaemon(daemon);
brokerthread.start();
}
public static class helloworldproducer implements runnable {
public void run() {
try {
// create a connectionfactory
activemqconnectionfactory connectionfactory = new activemqconnectionfactory(vm://localhost);
// create a connection
connection connection = connectionfactory.createconnection();
connection.start();
// create a session
session session = connection.createsession(false, session.auto_acknowledge);
// create the destination (topic or queue)
destination destination = session.createqueue(test.foo);
// create a messageproducer from the session to the topic or queue
messageproducer producer = session.createproducer(destination);
producer.setdeliverymode(deliverymode.non_persistent);
// create a messages
string text = hello world! from: + thread.currentthread().getname() + : + this.hashcode();
textmessage message = session.createtextmessage(text);
// tell the producer to send the message
system.out.println(sent message: + message.hashcode() + : + thread.currentthread().getname());
producer.send(message);
// clean up
//producer.close();
session.close();
connection.close();
}
catch (exception e) {
system.out.println(caught: + e);
e.printstacktrace();
}
}
}
public static class helloworldconsumer implements runnable, exceptionlistener {
public void run() {
try {
// create a connectionfactory
activemqconnectionfactory connectionfactory = new activemqconnectionfactory(vm://localhost);
// create a connection
connection connection = connectionfactory.createconnection();
connection.start();
connection.setexceptionlistener(this);
// create a session
session session = connection.createsession(false, session.auto_acknowledge);
// create the destination (topic or queue)
destination destination = session.createqueue(test.foo);
// create a messageconsumer from the session to the topic or queue
messageconsumer consumer = session.createconsumer(destination);
// wait for a message
message message = consumer.receive(1000);
if (message instanceof textmessage) {
textmessage textmessage = (textmessage) message;
string text = textmessage.gettext();
system.out.println(received: + text);
} else {
system.out.println(received: + message);
}
consumer.close();
session.close();
connection.close();
} catch (exception e) {
system.out.println(caught: + e);
e.printstacktrace();
}
}
public synchronized void onexception(jmsexception ex) {
system.out.println(jms exception occured. shutting down client.);
}
}
}
faq常见问题:1 activemq重新连接机制: 生产者或消费者配置实例:
private string url = failover:(tcp://192.168.4.170:61616?wireformat.maxinactivityduration=1000);
activemqconnectionfactory factory = new activemqconnectionfactory(url)
failover机制原理:
activemq uses a keepalive protocol on top of its transports, to keep firewalls open and also detect whether the broker is no longer reachable.
the keepalive protocol periodically sends a lightweight command message to the broker, and expects a response. if it dosen't receive one within a given time period,
acitvemq will assume that the transport is no longer walid. the failover transport listens for failed transports and will select another transport to use on such a failure.
参考:
[1]《activemq-in-action-manning》 12.5 surviving network or broker failure with the failover protocol
[2] activemq重新连接机制 参考:http://jinguo.iteye.com/blog/243514