欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ActiveMQ安装与使用

程序员文章站 2024-03-04 12:22:41
...

定义

ActiveMQ Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位

 

JMSJava Messaging Service)是Java平台上有关面向消息中间件的技术规范,翻译为Java消息服务

 

应用场景

异步消息处理

 

 

安装

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

Windows环境,下载后解压直接运行/bin/activemq.bat即可

 

后台地址:http://localhost:8161/

 

生产者端代码:

ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
        activeMQConnectionFactory.setBrokerURL("tcp://192.168.1.83:61616");
        activeMQConnectionFactory.setUserName("admin");
        activeMQConnectionFactory.setPassword("admin");


        PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory);
        pooledConnectionFactory.setMaximumActiveSessionPerConnection(100);
        pooledConnectionFactory.setIdleTimeout(300000);
        pooledConnectionFactory.setBlockIfSessionPoolIsFull(true);
        pooledConnectionFactory.setMaxConnections(100);

        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(pooledConnectionFactory);

        ActiveMQQueue testqueue = new ActiveMQQueue("testqueue");

DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer();
        defaultMessageListenerContainer.setConnectionFactory(pooledConnectionFactory);
        defaultMessageListenerContainer.setDestination(testqueue);
        defaultMessageListenerContainer.setMessageListener(testQueueMQListener);

        try {
            Connection connection = jmsTemplate.getConnectionFactory().createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(testqueue);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            for(int i = 0; i < 10; i ++) {
                TextMessage msg = session.createTextMessage("this is test, num:" + i);
                producer.send(msg);
            }

            connection.close();
        }catch (JMSException e) {
            e.printStackTrace();
        }

 

监听端代码:

 

// ConnectionFactory :连接工厂,JMS 用它创建连接
        ConnectionFactory connectionFactory;
        // Connection :JMS 客户端到JMS Provider 的连接
        Connection connection = null;
        // Session: 一个发送或接收消息的线程
        Session session;
        // Destination :消息的目的地;消息发送给谁.
        Destination destination;
        // 消费者,消息接收者
        MessageConsumer consumer;
        connectionFactory = new ActiveMQConnectionFactory(
            ActiveMQConnection.DEFAULT_USER,
            ActiveMQConnection.DEFAULT_PASSWORD,
            "tcp://192.168.1.83:61616");
        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            session = connection.createSession(Boolean.FALSE,
                                               Session.AUTO_ACKNOWLEDGE);

            destination = session.createQueue("testqueue");
            consumer = session.createConsumer(destination);
            while (true) {
                //设置接收者接收消息的时间
                TextMessage message = (TextMessage) consumer.receive(1000);
                if (null != message) {
                    System.out.println("收到消息:" + message.getText());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }

 

 

 

 

 

通过spring整合:

spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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-3.0.xsd">
   
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="${ActiveMQ.brokerURL}"/>
        <property name="userName" value="${ActiveMQ.userName}"/>
        <property name="password" value="${ActiveMQ.password}"/>
    </bean>

   <bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
      <property name="connectionFactory" ref="targetConnectionFactory" />
      <!-- 每个连接的最大活动会话,默认500 -->
      <property name="maximumActiveSessionPerConnection" value="100" />
      <!-- 空闲连接超时时间,单位:毫秒 -->
      <property name="idleTimeout" value="300000" />
      <!-- 如果连接池是满的,则阻塞 -->
      <property name="blockIfSessionPoolIsFull" value="true" />
      <!-- 最大连接数 -->
      <property name="maxConnections" value="100" />
   </bean>

   <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <!--<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
       <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>-->
    
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>
      
   
    <!--搜索引擎更新队列目的地-->
    <bean id="searchIndexDestination" class="org.apache.activemq.command.ActiveMQQueue">
       <constructor-arg value="searchIndex"/>
    </bean>

    <!--这个是主题目的地,一对多的
    <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
       <constructor-arg value="topic"/>
    </bean>
    -->
    
    <!-- 搜索引擎消息监听器 -->
    <bean id="searchIndexMQListener" class="com.mm.listener.SearchIndexMQListener" >
       <property name="searchBuildCache" ref="searchBuildCache"/>
    </bean>

    <!-- 搜索引擎消息监听容器 -->
    <bean id="searchIndexJmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
       <property name="connectionFactory" ref="connectionFactory" />
       <property name="destination" ref="searchIndexDestination" />
       <property name="messageListener" ref="searchIndexMQListener" />
    </bean>


    <!--通用更新队列目的地-->
    <bean id="commonQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
       <constructor-arg value="commonQueue"/>
    </bean>

   <!-- 通用消息监听器 -->
   <bean id="commonQueueMQListener" class="com.mm.listener.CommonQueueMQListener">
      <property name="solrOwnJoinFacade" ref="solrOwnJoinFacade"/>
   </bean>

   <!-- 通用消息监听容器 -->
   <bean id="commonQueueJmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
      <property name="connectionFactory" ref="connectionFactory" />
      <property name="destination" ref="commonQueueDestination" />
      <property name="messageListener" ref="commonQueueMQListener" />
   </bean>

    <bean id="producerService" class="com.mm.jms.ProducerServiceImpl">
       <property name="jmsTemplate" ref="jmsTemplate"/>
       <property name="destinationMap">
          <map>
             <entry key="searchIndexDestination">
                <ref bean="searchIndexDestination"/>
             </entry>
             <entry key="commonQueueDestination">
                <ref bean="commonQueueDestination"/>
             </entry>
          </map>
       </property>
    </bean>
   

</beans>

 生产者端代码:

public class ProducerServiceImpl implements ProducerService {
    private JmsTemplate jmsTemplate;
    private Map<String, Destination> destinationMap;
    

    @Override
    public void sendTextMessage(DestinationTypeName typeName, String message) {
        try {

            Destination destination = destinationMap.get(typeName.getTypeName());
            if(destination == null) {
                return;
            }
            Connection connection = jmsTemplate.getConnectionFactory().createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            TextMessage msg = session.createTextMessage(message);
            producer.send(msg);
            connection.close();
        }catch (JMSException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendObjectMessage(DestinationTypeName typeName, JmsObjectMessage jmsObjectMessage) {
        try {

            Destination destination = destinationMap.get(typeName.getTypeName());
            if(destination == null) {
                return;
            }
            Connection connection = jmsTemplate.getConnectionFactory().createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            ObjectMessage msg = session.createObjectMessage(jmsObjectMessage);
            producer.send(msg);
            connection.close();
        }catch (JMSException e) {
            e.printStackTrace();
        }
    }

    private static String env(String key, String defaultValue) {
        String rc = System.getenv(key);
        if( rc== null )
            return defaultValue;
        return rc;
    }

    private static String arg(String []args, int index, String defaultValue) {
        if( index < args.length )
            return args[index];
        else
            return defaultValue;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setDestinationMap(Map<String, Destination> destinationMap) {
        this.destinationMap = destinationMap;
    }
}

 

监听端代码:

public class CommonQueueMQListener implements MessageListener {
    private static Log logger = LogFactory.getLog(CommonQueueMQListener.class);
    private SolrOwnJoinFacade solrOwnJoinFacade;

    @Override
    public void onMessage(Message message) {
        if(message instanceof TextMessage){
            TextMessage textMsg = (TextMessage) message;

            logger.debug(textMsg);

        }else if(message instanceof ObjectMessage) {
            ObjectMessage objMsg = (ObjectMessage) message;
            try {
                if(objMsg.getObject() instanceof OwnJoinIndexMQBean) {
                    OwnJoinIndexMQBean ownJoinIndexMQBean=(OwnJoinIndexMQBean) objMsg.getObject();
                    solrOwnJoinFacade.updateSolrIndex(ownJoinIndexMQBean.getNid());
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

    }

    public void setSolrOwnJoinFacade(SolrOwnJoinFacade solrOwnJoinFacade) {
        this.solrOwnJoinFacade = solrOwnJoinFacade;
    }
}