ActiveMQ用戶端配置使用

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   color   

一、通過JNDI來使用ActiveMQ

1、jndi配置JMS對象

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory # use the following property to configure the default connectorjava.naming.provider.url = vm://localhost # use the following property to specify the JNDI name the connection factory# should appear as.#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry # register some queues in JNDI using the form# queue.[jndiName] = [physicalName]queue.MyQueue = example.MyQueue  # register some topics in JNDI using the form# topic.[jndiName] = [physicalName]topic.MyTopic = example.MyTopic

2、用戶端代碼使用

// create a new intial context, which loads from jndi.properties filejavax.naming.Context ctx = new javax.naming.InitialContext();// lookup the connection factoryjavax.jms.TopicConnectionFactory factory = (javax.jms.TopicConnectionFactory)ctx.lookup("ConnectionFactory");// create a new TopicConnection for pub/sub messagingjavax.jms.TopicConnection conn = factory.getTopicConnection();// lookup an existing topicjavax.jms.Topic mytopic = (javax.jms.Topic)ctx.lookup("MyTopic");// create a new TopicSession for the clientjavax.jms.TopicSession session = conn.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE);// create a new subscriber to receive messagesjavax.jms.TopicSubscriber subscriber = session.createSubscriber(mytopic);

Notice the name of the topic in the sample is "MyTopic". ActiveMQ will read the jndi.properties files and creates the topics and queues in a lazy fashion. The prefix topic and queue is stripped, so the jndi name begins after the prefix.

Once you have the jndi.properties edited and ready, it needs to be accessible to your application. The easiest way is to add jndi.properties to a jar file. When "new InitialContext()" is called, it will scan the resources and find the file. If you get "javax.naming.NamingException", it usually means the jndi.properties file is not accessible.

 

3、通過Porperties來設定

Properties props = new Properties();props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");props.setProperty(Context.PROVIDER_URL,"tcp://hostname:61616");javax.naming.Context ctx = new InitialContext(props);

4、Example Java Code

import javax.jms.Connection;import javax.jms.ConnectionFactory;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.MessageProducer;import javax.jms.Session;import javax.jms.TextMessage;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException; import org.slf4j.Logger;import org.slf4j.LoggerFactory; /** * A simple polymorphic JMS producer which can work with Queues or Topics which * uses JNDI to lookup the JMS connection factory and destination * * */public final class SimpleProducer {     private static final Logger LOG = LoggerFactory.getLogger(SimpleProducer.class);     private SimpleProducer() {    }     /**     * @param args the destination name to send to and optionally, the number of     *                messages to send     */    public static void main(String[] args) {        Context jndiContext = null;        ConnectionFactory connectionFactory = null;        Connection connection = null;        Session session = null;        Destination destination = null;        MessageProducer producer = null;        String destinationName = null;        final int numMsgs;         if ((args.length < 1) || (args.length > 2)) {            LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]");            System.exit(1);        }        destinationName = args[0];        LOG.info("Destination name is " + destinationName);        if (args.length == 2) {            numMsgs = (new Integer(args[1])).intValue();        } else {            numMsgs = 1;        }         /*         * Create a JNDI API InitialContext object         */        try {            jndiContext = new InitialContext();        } catch (NamingException e) {            LOG.info("Could not create JNDI API context: " + e.toString());            System.exit(1);        }         /*         * Look up connection factory and destination.         */        try {            connectionFactory = (ConnectionFactory)jndiContext.lookup("ConnectionFactory");            destination = (Destination)jndiContext.lookup(destinationName);        } catch (NamingException e) {            LOG.info("JNDI API lookup failed: " + e);            System.exit(1);        }         /*         * Create connection. Create session from connection; false means         * session is not transacted. Create sender and text message. Send         * messages, varying text slightly. Send end-of-messages message.         * Finally, close connection.         */        try {            connection = connectionFactory.createConnection();            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);            producer = session.createProducer(destination);            TextMessage message = session.createTextMessage();            for (int i = 0; i < numMsgs; i++) {                message.setText("This is message " + (i + 1));                LOG.info("Sending message: " + message.getText());                producer.send(message);            }             /*             * Send a non-text control message indicating end of messages.             */            producer.send(session.createMessage());        } catch (JMSException e) {            LOG.info("Exception occurred: " + e);        } finally {            if (connection != null) {                try {                    connection.close();                } catch (JMSException e) {                }            }        }    }}

二、使用spring來使用ActiveMQ

1、使用spring配置ConnectionFactory

<bean id="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">    <property name="brokerURL">      <value>tcp://localhost:61616</value>    </property>  </bean>

或者使用Zeroconf來查詢可用的brokers

<bean id="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">    <property name="brokerURL">      <value>zeroconf://_activemq.broker.development.</value>    </property>  </bean>

如果是使用的是spring2.0以上版本,則不需要顯式配置factory bean

<beans  xmlns="http://www.springframework.org/schema/beans"  xmlns:amq="http://activemq.apache.org/schema/core"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">   <amq:broker useJmx="false" persistent="false">    <amq:transportConnectors>      <amq:transportConnector uri="tcp://localhost:0" />    </amq:transportConnectors>  </amq:broker>   <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost"/></beans>

2、配置使用JmsTemplate,此處使用了ActiveMQ內建的串連池

!-- a pooling based JMS provider -->  <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">    <property name="connectionFactory">      <bean class="org.apache.activemq.ActiveMQConnectionFactory">        <property name="brokerURL">          <value>tcp://localhost:61616</value>        </property>      </bean>    </property>  </bean>   <!-- Spring JMS Template -->  <bean id="myJmsTemplate" class="org.springframework.jms.core.JmsTemplate">    <property name="connectionFactory">      <ref local="jmsFactory"/>    </property>  </bean>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.