ActiveMQ 通过JMX监控Connection,Queue,Topic的信息

来源:互联网 发布:数码大师软件多大 编辑:程序博客网 时间:2024/06/06 21:14

How can I monitor ActiveMQ

In ActiveMQ 4.x you can monitor the broker to see what destinations are being used, their activity along with connections and subscriptions using the following tools

  • JMX and a JMX console such as jConsole
  • The Web Console
  • the Advisory Message feature (using JMS messages to monitor the system)
  • The Command Agent; ActiveMQ.Agent topic that you query for status
  • The Visualisation plug-in
  • The Statistics plug-in (from 5.3)

 

Java代码  收藏代码
  1. package easyway.app.activemq.demo.monitors;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.Collection;  
  6. import java.util.Collections;  
  7. import java.util.Iterator;  
  8. import java.util.List;  
  9. import java.util.Set;  
  10.   
  11. import javax.jms.Connection;  
  12. import javax.jms.Destination;  
  13. import javax.jms.JMSException;  
  14. import javax.jms.MessageConsumer;  
  15. import javax.jms.MessageProducer;  
  16. import javax.jms.Session;  
  17. import javax.jms.TextMessage;  
  18. import javax.management.ObjectName;  
  19. import javax.management.QueryExp;  
  20.   
  21. import org.apache.activemq.ActiveMQConnection;  
  22. import org.apache.activemq.ActiveMQConnectionFactory;  
  23. import org.apache.activemq.broker.Broker;  
  24. import org.apache.activemq.broker.BrokerService;  
  25. import org.apache.activemq.broker.jmx.BrokerView;  
  26. import org.apache.activemq.broker.jmx.BrokerViewMBean;  
  27. import org.apache.activemq.broker.jmx.ConnectionViewMBean;  
  28. import org.apache.activemq.broker.jmx.ConnectorViewMBean;  
  29. import org.apache.activemq.broker.jmx.DestinationViewMBean;  
  30. import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean;  
  31. import org.apache.activemq.broker.jmx.JobSchedulerViewMBean;  
  32. import org.apache.activemq.broker.jmx.ManagedRegionBroker;  
  33. import org.apache.activemq.broker.jmx.ManagementContext;  
  34. import org.apache.activemq.broker.jmx.NetworkBridgeViewMBean;  
  35. import org.apache.activemq.broker.jmx.NetworkConnectorViewMBean;  
  36. import org.apache.activemq.broker.jmx.QueueViewMBean;  
  37. import org.apache.activemq.broker.jmx.SubscriptionViewMBean;  
  38. import org.apache.activemq.broker.jmx.TopicViewMBean;  
  39. import org.apache.activemq.broker.region.Queue;  
  40. import org.apache.activemq.broker.region.policy.ConstantPendingMessageLimitStrategy;  
  41. import org.apache.activemq.broker.region.policy.PolicyEntry;  
  42. import org.apache.activemq.broker.region.policy.PolicyMap;  
  43. import org.apache.activemq.command.ActiveMQDestination;  
  44. import org.apache.activemq.transport.TransportListener;  
  45. import org.apache.activemq.usage.MemoryUsage;  
  46. import org.apache.activemq.usage.StoreUsage;  
  47. import org.apache.activemq.usage.SystemUsage;  
  48. import org.apache.activemq.usage.TempUsage;  
  49. import org.apache.commons.lang.StringUtils;  
  50. import org.apache.commons.lang.builder.ToStringBuilder;  
  51. import org.apache.commons.lang.builder.ToStringStyle;  
  52. import org.slf4j.Logger;  
  53. import org.slf4j.LoggerFactory;  
  54.   
  55. /** 
  56.  * 监控ActiveMQ的各种信息Broker,Connection,Queue,Topic的数量和压栈和出栈 
  57.  * @author longgangbai 
  58.  * 
  59.  */  
  60. public class ActiveMQMonitor {  
  61.        private static final transient Logger LOG = LoggerFactory.getLogger(DestinationSourceMonitor.class);  
  62.           
  63.         protected static final int MESSAGE_COUNT = 2000;  
  64.         protected BrokerService brokerService;  
  65.         protected Connection connection;  
  66.         protected String bindAddress ="tcp://localhost:61619";  
  67.         //ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL;  
  68.         protected int topicCount;  
  69.   
  70.         /** 
  71.          * 获取Broker 的AdminView对象 
  72.          * @return 
  73.          * @throws Exception 
  74.          */  
  75.         public BrokerViewMBean getBrokerAdmin() throws Exception {  
  76.             return brokerService.getAdminView();  
  77.         }  
  78.         /** 
  79.          * 获取所有的QueueViewMBean的 
  80.          * @return 
  81.          * @throws Exception 
  82.          */  
  83.         public Collection<QueueViewMBean> getQueues() throws Exception {  
  84.             BrokerViewMBean broker = getBrokerAdmin();  
  85.             if (broker == null) {  
  86.                 return Collections.EMPTY_LIST;  
  87.             }  
  88.             ObjectName[] queues = broker.getQueues();  
  89.             return getManagedObjects(queues, QueueViewMBean.class);  
  90.         }  
  91.           
  92.           
  93.         /** 
  94.          * 获取所有TopicViewMBean 
  95.          * @return 
  96.          * @throws Exception 
  97.          */  
  98.         public Collection<TopicViewMBean> getTopics() throws Exception {  
  99.             BrokerViewMBean broker = getBrokerAdmin();  
  100.             if (broker == null) {  
  101.                 return Collections.EMPTY_LIST;  
  102.             }  
  103.             ObjectName[] queues = broker.getTopics();  
  104.             return getManagedObjects(queues, TopicViewMBean.class);  
  105.         }  
  106.         /** 
  107.          * 获取所有DurableSubscriptionViewMBean 
  108.          * @return 
  109.          * @throws Exception 
  110.          */  
  111.         public Collection<DurableSubscriptionViewMBean> getDurableTopicSubscribers()  
  112.                 throws Exception {  
  113.             BrokerViewMBean broker = getBrokerAdmin();  
  114.             if (broker == null) {  
  115.                 return Collections.EMPTY_LIST;  
  116.             }  
  117.             ObjectName[] queues = broker.getDurableTopicSubscribers();  
  118.             return getManagedObjects(queues, DurableSubscriptionViewMBean.class);  
  119.         }  
  120.         /** 
  121.          * 获取所有DurableSubscriptionViewMBean 
  122.          * @return 
  123.          * @throws Exception 
  124.          */  
  125.         public Collection<DurableSubscriptionViewMBean> getInactiveDurableTopicSubscribers()  
  126.                 throws Exception {  
  127.             BrokerViewMBean broker = getBrokerAdmin();  
  128.             if (broker == null) {  
  129.                 return Collections.EMPTY_LIST;  
  130.             }  
  131.             ObjectName[] queues = broker.getInactiveDurableTopicSubscribers();  
  132.             return getManagedObjects(queues, DurableSubscriptionViewMBean.class);  
  133.         }  
  134.         /** 
  135.          * 根据queueName获取queue相关的信息 
  136.          * @return 
  137.          * @throws Exception 
  138.          */  
  139.         public QueueViewMBean getQueue(String name) throws Exception {  
  140.             return (QueueViewMBean) getDestinationByName(getQueues(), name);  
  141.         }  
  142.         /** 
  143.          * 根据topicName获取Topic相关的信息 
  144.          * @return 
  145.          * @throws Exception 
  146.          */  
  147.         public TopicViewMBean getTopic(String name) throws Exception {  
  148.             return (TopicViewMBean) getDestinationByName(getTopics(), name);  
  149.         }  
  150.         /** 
  151.          * 获取DestinationViewMBean 
  152.          * @return 
  153.          * @throws Exception 
  154.          */  
  155.         protected DestinationViewMBean getDestinationByName(  
  156.                 Collection<? extends DestinationViewMBean> collection, String name) {  
  157.             Iterator<? extends DestinationViewMBean> iter = collection.iterator();  
  158.             while (iter.hasNext()) {  
  159.                 DestinationViewMBean destinationViewMBean = iter.next();  
  160.                 if (name.equals(destinationViewMBean.getName())) {  
  161.                     return destinationViewMBean;  
  162.                 }  
  163.             }  
  164.             return null;  
  165.         }  
  166.         /** 
  167.          * 获取所有Mananage 
  168.          * @return 
  169.          * @throws Exception 
  170.          */  
  171.         @SuppressWarnings("unchecked")  
  172.         protected <T> Collection<T> getManagedObjects(ObjectName[] names,  
  173.                 Class<T> type) throws Exception {  
  174.             List<T> answer = new ArrayList<T>();  
  175.             for (int i = 0; i < names.length; i++) {  
  176.                 ObjectName name = names[i];  
  177.                 T value = (T) newProxyInstance(name, type, true);  
  178.                 if (value != null) {  
  179.                     answer.add(value);  
  180.                 }  
  181.             }  
  182.             return answer;  
  183.         }  
  184.         /** 
  185.          * 获取所有ConnectionViewMBean 
  186.          * @return 
  187.          * @throws Exception 
  188.          */  
  189.         @SuppressWarnings("unchecked")  
  190.         public Collection<ConnectionViewMBean> getConnections() throws Exception {  
  191.             String brokerName = getBrokerName();  
  192.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  193.                     + brokerName + ",Type=Connection,*");  
  194.             Set<ObjectName> queryResult = queryNames(query, null);  
  195.             return getManagedObjects(queryResult.toArray(new ObjectName[queryResult  
  196.                     .size()]), ConnectionViewMBean.class);  
  197.         }  
  198.         /** 
  199.          * 获取所有Connections 
  200.          * @return 
  201.          * @throws Exception 
  202.          */  
  203.         @SuppressWarnings("unchecked")  
  204.         public Collection<String> getConnections(String connectorName)  
  205.                 throws Exception {  
  206.             String brokerName = getBrokerName();  
  207.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  208.                     + brokerName + ",Type=Connection,ConnectorName="  
  209.                     + connectorName + ",*");  
  210.             Set<ObjectName> queryResult = queryNames(query, null);  
  211.             Collection<String> result = new ArrayList<String>(queryResult.size());  
  212.             for (ObjectName on : queryResult) {  
  213.                 String name = StringUtils.replace(on.getKeyProperty("Connection"),  
  214.                         "_"":");  
  215.                 result.add(name);  
  216.             }  
  217.             return result;  
  218.         }  
  219.         /** 
  220.          * 获取所有ConnectionViewMBean 
  221.          * @return 
  222.          * @throws Exception 
  223.          */  
  224.         @SuppressWarnings("unchecked")  
  225.         public ConnectionViewMBean getConnection(String connectionName)  
  226.                 throws Exception {  
  227.             connectionName = StringUtils.replace(connectionName, ":""_");  
  228.             String brokerName = getBrokerName();  
  229.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  230.                     + brokerName + ",Type=Connection,*,Connection="  
  231.                     + connectionName);  
  232.             Set<ObjectName> queryResult = queryNames(query, null);  
  233.             if (queryResult.size() == 0)  
  234.                 return null;  
  235.             ObjectName objectName = queryResult.iterator().next();  
  236.             return (ConnectionViewMBean) newProxyInstance(objectName,  
  237.                     ConnectionViewMBean.classtrue);  
  238.         }  
  239.   
  240.         @SuppressWarnings("unchecked")  
  241.         public Collection<String> getConnectors() throws Exception {  
  242.             String brokerName = getBrokerName();  
  243.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  244.                     + brokerName + ",Type=Connector,*");  
  245.             Set<ObjectName> queryResult = queryNames(query, null);  
  246.             Collection<String> result = new ArrayList<String>(queryResult.size());  
  247.             for (ObjectName on : queryResult)  
  248.                 result.add(on.getKeyProperty("ConnectorName"));  
  249.             return result;  
  250.         }  
  251.   
  252.         public ConnectorViewMBean getConnector(String name) throws Exception {  
  253.             String brokerName = getBrokerName();  
  254.             ObjectName objectName = new ObjectName(  
  255.                     "org.apache.activemq:BrokerName=" + brokerName  
  256.                             + ",Type=Connector,ConnectorName=" + name);  
  257.             return (ConnectorViewMBean) newProxyInstance(objectName,  
  258.                     ConnectorViewMBean.classtrue);  
  259.         }  
  260.   
  261.         @SuppressWarnings("unchecked")  
  262.         public Collection<NetworkConnectorViewMBean> getNetworkConnectors()  
  263.                 throws Exception {  
  264.             String brokerName = getBrokerName();  
  265.               
  266.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  267.                     + brokerName + ",Type=NetworkConnector,*");  
  268.             Set<ObjectName> queryResult = queryNames(query, null);  
  269.             return getManagedObjects(queryResult.toArray(new ObjectName[queryResult  
  270.                     .size()]), NetworkConnectorViewMBean.class);  
  271.         }  
  272.   
  273.         public Collection<NetworkBridgeViewMBean> getNetworkBridges()  
  274.                 throws Exception {  
  275.             String brokerName = getBrokerName();  
  276.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  277.                     + brokerName + ",Type=NetworkBridge,*");  
  278.             Set<ObjectName> queryResult = queryNames(query, null);  
  279.             return getManagedObjects(queryResult.toArray(new ObjectName[queryResult  
  280.                     .size()]), NetworkBridgeViewMBean.class);  
  281.         }  
  282.   
  283.         @SuppressWarnings("unchecked")  
  284.         public Collection<SubscriptionViewMBean> getQueueConsumers(String queueName)  
  285.                 throws Exception {  
  286.             String brokerName = getBrokerName();  
  287.             queueName = StringUtils.replace(queueName, "\"""_");  
  288.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  289.                     + brokerName  
  290.                     + ",Type=Subscription,destinationType=Queue,destinationName="  
  291.                     + queueName + ",*");  
  292.             Set<ObjectName> queryResult = queryNames(query, null);  
  293.             return getManagedObjects(queryResult.toArray(new ObjectName[queryResult  
  294.                     .size()]), SubscriptionViewMBean.class);  
  295.         }  
  296.   
  297.         @SuppressWarnings("unchecked")  
  298.         public Collection<SubscriptionViewMBean> getConsumersOnConnection(  
  299.                 String connectionName) throws Exception {  
  300.             connectionName = StringUtils.replace(connectionName, ":""_");  
  301.             String brokerName = getBrokerName();  
  302.             ObjectName query = new ObjectName("org.apache.activemq:BrokerName="  
  303.                     + brokerName + ",Type=Subscription,clientId=" + connectionName  
  304.                     + ",*");  
  305.             Set<ObjectName> queryResult = queryNames(query, null);  
  306.             return getManagedObjects(queryResult.toArray(new ObjectName[queryResult  
  307.                     .size()]), SubscriptionViewMBean.class);  
  308.         }  
  309.         /** 
  310.          * 获取定时执行的队列的信息 
  311.          * @return 
  312.          * @throws Exception 
  313.          */  
  314.         public JobSchedulerViewMBean getJobScheduler() throws Exception {  
  315.             ObjectName name = getBrokerAdmin().getJMSJobScheduler();  
  316.             return (JobSchedulerViewMBean) newProxyInstance(name,  
  317.                     JobSchedulerViewMBean.classtrue);  
  318.         }  
  319.   
  320.         public String getBrokerName() throws Exception {  
  321.             return brokerService.getBrokerName();  
  322.         }  
  323.         /** 
  324.          * 获取Broker对象 
  325.          * @return 
  326.          * @throws Exception 
  327.          */  
  328.         public Broker getBroker() throws Exception {  
  329.             return brokerService.getBroker();  
  330.         }  
  331.         public ManagementContext getManagementContext() {  
  332.             return brokerService.getManagementContext();  
  333.         }  
  334.   
  335.         public ManagedRegionBroker getManagedBroker() throws Exception {  
  336.             BrokerView adminView = brokerService.getAdminView();  
  337.             if (adminView == null) {  
  338.                 return null;  
  339.             }  
  340.             return adminView.getBroker();  
  341.         }  
  342.   
  343.         public void purgeQueue(ActiveMQDestination destination) throws Exception {  
  344.             Set destinations = getManagedBroker().getQueueRegion().getDestinations(destination);  
  345.             for (Iterator i = destinations.iterator(); i.hasNext();) {  
  346.                 Destination dest = (Destination) i.next();  
  347.                 if (dest instanceof Queue) {  
  348.                     Queue regionQueue = (Queue) dest;  
  349.                     regionQueue.purge();  
  350.                 }  
  351.             }  
  352.         }  
  353.         /** 
  354.          *  
  355.          * @param name 
  356.          * @param query 
  357.          * @return 
  358.          * @throws Exception 
  359.          */  
  360.         public Set queryNames(ObjectName name, QueryExp query) throws Exception {  
  361.             return getManagementContext().queryNames(name, query);  
  362.         }  
  363.         /** 
  364.          * 通过JMX获取ActiveMQ各种信息 
  365.          * @param objectName 
  366.          * @param interfaceClass 
  367.          * @param notificationBroadcaster 
  368.          * @return 
  369.          */  
  370.         public Object newProxyInstance(ObjectName objectName, Class interfaceClass, boolean notificationBroadcaster) {  
  371.             return getManagementContext().newProxyInstance(objectName, interfaceClass, notificationBroadcaster);  
  372.         }  
  373.         /** 
  374.          * 监控内存信息 
  375.          * @throws Exception 
  376.          */  
  377.         public void monitorMermeryUsage() throws Exception{  
  378.             SystemUsage proSystemUsage=brokerService.getProducerSystemUsage();  
  379.             printSystemUsage(proSystemUsage);  
  380.             SystemUsage syUage=brokerService.getSystemUsage();  
  381.             printSystemUsage(syUage);  
  382.             SystemUsage consumsyUage=brokerService.getConsumerSystemUsage();  
  383.             printSystemUsage(consumsyUage);  
  384.         }  
  385.           
  386.         /** 
  387.          * 打印内存信息 
  388.          * @param syUage 
  389.          */  
  390.         public void printSystemUsage(SystemUsage syUage){  
  391.             String name=syUage.getName();  
  392.             LOG.info("SystemUsage name ="+name);  
  393.             MemoryUsage memeryUsage =syUage.getMemoryUsage();  
  394.             LOG.info("memeryUsage PercentUsage name ="+memeryUsage.getPercentUsage());  
  395.             LOG.info("memeryUsage Limit name ="+memeryUsage.getLimit());  
  396.             LOG.info("memeryUsage Usage name ="+memeryUsage.getUsage());  
  397.             TempUsage tempUsage =syUage.getTempUsage();  
  398.             LOG.info("tempUsage PercentUsage name ="+tempUsage.getPercentUsage());  
  399.             LOG.info("tempUsage Limit name ="+tempUsage.getLimit());  
  400.             LOG.info("tempUsage Usage name ="+tempUsage.getUsage());  
  401.             StoreUsage storeUsage=syUage.getStoreUsage();  
  402.             LOG.info("storeUsage PercentUsage name ="+storeUsage.getPercentUsage());  
  403.             LOG.info("storeUsage Limit name ="+storeUsage.getLimit());  
  404.             LOG.info("storeUsage Usage name ="+storeUsage.getUsage());  
  405.         }  
  406.         /** 
  407.          * 监控消息的方法 
  408.          * @throws Exception 
  409.          */  
  410.         public void monitorQueueAndTopic() throws Exception{  
  411.             LOG.info("==========Connection =================");  
  412.             Collection<ConnectionViewMBean> conVBean=getConnections();  
  413.             for (ConnectionViewMBean bean : conVBean) {  
  414.                 LOG.info("remoteAddress:"+bean.getRemoteAddress());  
  415.                 LOG.info("isActive:"+bean.isActive());  
  416.                 LOG.info("isConnected:"+bean.isConnected());  
  417.             }  
  418.             LOG.info("=============Topic =================");  
  419.             Collection<TopicViewMBean>  topicVBean=getTopics();  
  420.             for (TopicViewMBean topicbean : topicVBean) {  
  421.                 LOG.info("beanName ="+topicbean.getName());  
  422.                 LOG.info("ConsumerCount ="+topicbean.getConsumerCount());  
  423.                 LOG.info("DequeueCount ="+topicbean.getDequeueCount());  
  424.                 LOG.info("EnqueueCount ="+topicbean.getEnqueueCount());  
  425.                 LOG.info("DispatchCount ="+topicbean.getDispatchCount());  
  426.                 LOG.info("ExpiredCount ="+topicbean.getExpiredCount());  
  427.                 LOG.info("MaxEnqueueTime ="+topicbean.getMaxEnqueueTime());  
  428.                 LOG.info("ProducerCount ="+topicbean.getProducerCount());  
  429.                 LOG.info("MemoryPercentUsage ="+topicbean.getMemoryPercentUsage());  
  430.                 LOG.info("MemoryLimit ="+topicbean.getMemoryLimit());  
  431.             }  
  432.             LOG.info("============Queue===================");  
  433.             Collection<QueueViewMBean> queuqVBeanList=getQueues();  
  434.             for (QueueViewMBean queuebean : queuqVBeanList) {  
  435.                 LOG.info(" queue beanName ="+queuebean.getName());  
  436.                 LOG.info("ConsumerCount ="+queuebean.getConsumerCount());  
  437.                 LOG.info("DequeueCount ="+queuebean.getDequeueCount());  
  438.                 LOG.info("EnqueueCount ="+queuebean.getEnqueueCount());  
  439.                 LOG.info("DispatchCount ="+queuebean.getDispatchCount());  
  440.                 LOG.info("ExpiredCount ="+queuebean.getExpiredCount());  
  441.                 LOG.info("MaxEnqueueTime ="+queuebean.getMaxEnqueueTime());  
  442.                 LOG.info("ProducerCount ="+queuebean.getProducerCount());  
  443.                 LOG.info("MemoryPercentUsage ="+queuebean.getMemoryPercentUsage());  
  444.                 LOG.info("MemoryLimit ="+queuebean.getMemoryLimit());  
  445.             }  
  446.         }  
  447.           
  448.         public void test() throws Exception{  
  449.             //获取初始化信息  
  450.             init();  
  451.             for (int i = 0; i < 10; i++) {  
  452.                 sendTopic(i);  
  453.             }  
  454.             for (int i = 0; i < 10; i++) {  
  455.                 sendPS(i);  
  456.             }  
  457.             monitorQueueAndTopic();           
  458.             Thread.sleep(5000);  
  459.             receiveTopic();  
  460.             receivePS();  
  461.         }  
  462.         /** 
  463.          * P2P发送方式 
  464.          * @throws JMSException 
  465.          */  
  466.         public void sendTopic(int i) throws JMSException{  
  467.             Session session=connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);  
  468.             Destination topic=session.createQueue("activemq.queue"+i);  
  469.             MessageProducer productor=(MessageProducer) session.createProducer(topic);  
  470.             TextMessage txtMessage =session.createTextMessage();  
  471.             txtMessage.setText("this is a topic message "+i);  
  472.             productor.send(txtMessage);  
  473.         }  
  474.         /** 
  475.          * Sub/Pub发送方式 
  476.          * @throws JMSException 
  477.          */  
  478.         public void sendPS(int i) throws JMSException{  
  479.             Session session=connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);  
  480.             Destination topic=session.createTopic("activemq.topic"+i);  
  481.             MessageProducer productor=(MessageProducer) session.createProducer(topic);  
  482.             TextMessage txtMessage =session.createTextMessage();  
  483.             txtMessage.setText("this is a topic message "+i);  
  484.             productor.send(txtMessage);  
  485.         }  
  486.           
  487.         /** 
  488.          * P2P接受方式 
  489.          * @throws JMSException 
  490.          */  
  491.         public void receiveTopic() throws JMSException{  
  492.             Session session=connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);  
  493.             Destination topic=session.createQueue("activemq.queue");  
  494.               
  495.             MessageConsumer consumer=(MessageConsumer) session.createConsumer(topic);  
  496.             TextMessage txtMessage =(TextMessage)consumer.receive();  
  497.             System.out.println("txtMessage ="+txtMessage.getText());  
  498.         }  
  499.         /** 
  500.          * Sub/Pub接受方式 
  501.          * @throws JMSException 
  502.          */  
  503.         public void receivePS() throws JMSException{  
  504.             Session session=connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);  
  505.             Destination topic=session.createQueue("activemq.topic");  
  506.               
  507.             MessageConsumer consumer=(MessageConsumer) session.createConsumer(topic);  
  508.             TextMessage txtMessage =(TextMessage)consumer.receive();  
  509.             System.out.println("txtMessage ="+txtMessage.getText());  
  510.         }  
  511.           
  512.           
  513.         /** 
  514.          * 初始化消息的方法 
  515.          * @throws Exception 
  516.          */  
  517.         protected void init() throws Exception {  
  518.             if (brokerService == null) {  
  519.                 brokerService = createBroker();  
  520.             }  
  521.             ActiveMQConnectionFactory factory = createConnectionFactory();  
  522.             connection = factory.createConnection();  
  523.             //添加Connection 的状态监控的方法  
  524.             monitorConnection(connection);  
  525.             //启动连接  
  526.             connection.start();  
  527.         }  
  528.           
  529.         /** 
  530.          * 监控台ActiveMQConnection的状态的方法 
  531.          * @param connection 
  532.          */  
  533.         public void monitorConnection(Connection connection){  
  534.             ActiveMQConnection activemqconnection =(ActiveMQConnection)connection;  
  535.             //添加ActiveMQConnection的监听类  
  536.             activemqconnection.addTransportListener(new TransportListener(){  
  537.   
  538.                 public void onCommand(Object object) {  
  539.                     LOG.info("onCommand  object "+object);  
  540.                       
  541.                 }  
  542.   
  543.                 public void onException(IOException ex) {  
  544.                     LOG.info("onException ="+ex.getMessage());  
  545.                 }  
  546.   
  547.                 public void transportInterupted() {  
  548.                     LOG.info("transportInterupted =");  
  549.                 }  
  550.   
  551.                 public void transportResumed() {  
  552.                     LOG.info("transportResumed .........");                   
  553.                 }  
  554.                   
  555.             });  
  556.         }  
  557.   
  558.         protected void destory() throws Exception {  
  559.             connection.close();  
  560.             if (brokerService != null) {  
  561.                 brokerService.stop();  
  562.             }  
  563.         }  
  564.         /** 
  565.          * 创建ActiveMQConnectionFactory 
  566.          * @return 
  567.          * @throws Exception 
  568.          */  
  569.         protected ActiveMQConnectionFactory createConnectionFactory()  
  570.                 throws Exception {  
  571.             ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(  
  572.                     bindAddress);  
  573.             return cf;  
  574.         }  
  575.   
  576.         /*** 
  577.          * 创建一个Broker监听进程 
  578.          * @return 
  579.          * @throws Exception 
  580.          */  
  581.         protected BrokerService createBroker() throws Exception {  
  582.             //创建BrokerService对象  
  583.             BrokerService answer = new BrokerService();  
  584.             //配置监听相关的信息  
  585.             configureBroker(answer);  
  586.             //启动Broker的启动  
  587.             answer.start();  
  588.               
  589.             return answer;  
  590.         }  
  591.   
  592.         /** 
  593.          * 配置Broker 
  594.          * @param answer 
  595.          * @throws Exception 
  596.          */  
  597.         protected void configureBroker(BrokerService answer) throws Exception {  
  598.             //创建持久化信息  
  599.             answer.setPersistent(false);  
  600.             //设置采用JMX管理  
  601.             answer.setUseJmx(true);  
  602.             ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy();  
  603.             strategy.setLimit(10);  
  604.             PolicyEntry tempQueueEntry = createPolicyEntry(strategy);  
  605.             tempQueueEntry.setTempQueue(true);  
  606.             PolicyEntry tempTopicEntry = createPolicyEntry(strategy);  
  607.             tempTopicEntry.setTempTopic(true);  
  608.             PolicyMap pMap = new PolicyMap();  
  609.             final List<PolicyEntry> policyEntries = new ArrayList<PolicyEntry>();  
  610.             policyEntries.add(tempQueueEntry);  
  611.             policyEntries.add(tempTopicEntry);  
  612.             pMap.setPolicyEntries(policyEntries);  
  613.             answer.setDestinationPolicy(pMap);  
  614.             //绑定url  
  615.             answer.addConnector(bindAddress);  
  616.             answer.setDeleteAllMessagesOnStartup(true);  
  617.         }  
  618.         /** 
  619.          * 创建一个配置策略 
  620.          * @param strategy 
  621.          * @return 
  622.          */  
  623.         private PolicyEntry createPolicyEntry(ConstantPendingMessageLimitStrategy strategy) {  
  624.             PolicyEntry policy = new PolicyEntry();  
  625.             policy.setAdvisdoryForFastProducers(true);  
  626.             policy.setAdvisoryForConsumed(true);  
  627.             policy.setAdvisoryForDelivery(true);  
  628.             policy.setAdvisoryForDiscardingMessages(true);  
  629.             policy.setAdvisoryForSlowConsumers(true);  
  630.             policy.setAdvisoryWhenFull(true);  
  631.             policy.setProducerFlowControl(false);  
  632.             policy.setPendingMessageLimitStrategy(strategy);  
  633.             return policy;  
  634.         }  
  635.           
  636.         public void object2string(Object object ){  
  637.             ToStringBuilder.reflectionToString(object, ToStringStyle.MULTI_LINE_STYLE);  
  638.         }  
  639.           
  640. }  

 

Java代码  收藏代码
  1. package easyway.app.activemq.demo.monitors;  
  2.   
  3. public class ActiveMQMonitorTest {  
  4.     public static void main(String[] args) throws Exception {  
  5.         ActiveMQMonitor monitor=new ActiveMQMonitor();  
  6.         monitor.test();  
  7.           
  8.     }  
  9. }
原文地址:http://topmanopensource.iteye.com/blog/1072846
0 0
原创粉丝点击