A simple understanding of the ActiveMQ message queue and a method of point to point and publish-subscribe implementation ActiveMQ

Apache ActiveMQ is developed by the Apache Software Foundation open source messaging middleware;

Since ActiveMQ is a pure Java program, so only operating system that supports Java Virtual Machine, ActiveMQ can be executed.

ActiveMQ is used to do?

To process the message, i.e. the processing of JMS. Message Queuing in a large e-commerce sites, such as Jingdong, Taobao, and other sites where to have in-depth application,

The main role of queues is to eliminate high peak concurrent access, speed up the response speed of the site.

Without the use of the message queue, the request of the user data directly into the database, in the case of high, the database will cause great pressure,

Also makes the system response delay increased, but the use of the queue, the queue sent to the user's request returns immediately.

For example: You can not submit orders directly to the user prompts successful, Jingdong Tip: "You submit the order,

Please wait for confirmation, "and then get the data from the message queue by the message queue of the consumer process, asynchronous write to the database.

Since the message queue service processing speed much faster than the database, the user's response delay can be effectively improved.

ActiveMQ usage scenarios?

1, asynchronous calls.

2, one to many communications.

3, a plurality of system integration done, homogeneous, heterogeneous.

4, as an alternative to the RPC.

5, a plurality of mutually decoupling applications.

6, as an event-driven architecture behind the scenes support.

7, in order to improve the scalability of the system.

ActiveMQ features?

Support for Java Message Service (JMS) 1.1 version

Spring Framework

Clusters (Clustering)

Supported programming languages include: C , C ++ , C # , Delphi , Erlang , Adobe Flash , Haskell , the Java , JavaScript , Perl , PHP , Pike , Python and Ruby

Protocol support includes: OpenWire, REST , STOMP, WS-the Notification, the MQTT, the XMPP and AMQP

How to install ActiveMQ?

Download: http://www.apache.org/dyn/closer.cgi?path=/activemq/apache-activemq/5.8.0/apache-activemq-5.8.0-bin.zip

Decompression to complete the installation of ActiveMQ

After extracting the directory structure as follows

 

 

If it is in the bin directory if it is below 32 to choose win32, 64 bit is selected and then click activemq.bat start win64

Three starts:

(1)普通启动 ./activemq start
(2)启动并指定日志文件 ./activemq start >tmp/smlog
(3)后台启动方式nohup ./activemq start >/tmp/smlog
前两种方式下在命令行窗口关闭时或者ctrl+c时导致进程退出,采用后台启动方式则可以避免这种情况

 

使用点对点的方式实现洗息队列

第一步:导入依赖

 <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-core</artifactId>
        <version>5.7.0</version>
    </dependency>

  

第二步:创建生产者

package com.wish.peertopeer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;

public class P2pProducer {
    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: 一个发送或接收消息的线程
        Session session = connection.createSession(Boolean.FALSE, 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);
        // 发送一条消息
        for (int i = 1; i <= 5; i++) {
            sendMsg(session, producer, i);
        }
        connection.close();
    }
    /**
     * 在指定的会话上,通过指定的消息生产者发出一条消息
     *
     * @param session
     *            消息会话
     * @param producer
     *            消息生产者
     */
    public static void sendMsg(Session session, MessageProducer producer, int i) throws JMSException {
        // 创建一条文本消息
        TextMessage message = session.createTextMessage("Hello ActiveMQ!" + i);
        // 通过消息生产者发出消息
        producer.send(message);
    }
}

  

第三步:创建消费者

package com.wish.peertopeer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class P2pConsumer {
    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: 一个发送或接收消息的线程
        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        // Destination :消息的目的地;消息发送给谁.
        // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
        Destination destination = session.createQueue("my-queue");
        // 消费者,消息接收者
        MessageConsumer consumer = session.createConsumer(destination);
        while (true) {
            TextMessage message = (TextMessage) consumer.receive();
            if (null != message) {
                System.out.println("收到消息:" + message.getText());
            } else
                break;
        }
        session.close();
        connection.close();
    }
}

  

实现效果

启动生产者

 

 

浏览http://localhost:8161/admin/queues.jsp查看

 

 

 

 

 

启动消费者

 

 

 

 

 浏览http://localhost:8161/admin/queues.jsp查看

 

 

使用发布订阅的方式实现消息队列

第一步:也是导入依赖与上面一样

第二步:创建生产者

package com.wish.publishandsubscribe;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class PapProducer {

    private static String BROKERURL = "tcp://127.0.0.1:61616";
    private static String TOPIC = "my-topic";

    public static void main(String[] args) throws JMSException {
        start();
    }

    static public void start() throws JMSException {
        System.out.println("生产者已经启动....");
        // 创建ActiveMQConnectionFactory 会话工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKERURL);
        Connection connection = activeMQConnectionFactory.createConnection();
        // 启动JMS 连接
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        send(producer, session);
        System.out.println("发送成功!");
        connection.close();
    }

    static public void send(MessageProducer producer, Session session) throws JMSException {
        for (int i = 1; i <= 5; i++) {
            System.out.println("我是消息" + i);
            TextMessage textMessage = session.createTextMessage("我是消息" + i);
            Destination destination = session.createTopic(TOPIC);
            producer.send(destination, textMessage);
        }
    }
}

  

第三步:创建消费者

 

package com.wish.publishandsubscribe;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
public class PapConsumer {
    private static String BROKERURL = "tcp://127.0.0.1:61616";
    private static String TOPIC = "my-topic";

    public static void main(String[] args) throws JMSException {
        start();
    }

    static public void start() throws JMSException {
        System.out.println("消费点启动...");
        // 创建ActiveMQConnectionFactory 会话工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKERURL);
        Connection connection = activeMQConnectionFactory.createConnection();
        // 启动JMS 连接
        connection.start();
        // 不开消息启事物,消息主要发送消费者,则表示消息已经签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 创建一个队列
        Topic topic = session.createTopic(TOPIC);
        MessageConsumer consumer = session.createConsumer(topic);
        // consumer.setMessageListener(new MsgListener());
        while (true) {
            TextMessage textMessage = (TextMessage) consumer.receive();
            if (textMessage != null) {
                System.out.println("接受到消息:" + textMessage.getText());
                // textMessage.acknowledge();// 手动签收
                // session.commit();
            } else {
                break;
            }
        }
        connection.close();
    }
}

  

实现效果

启动生产者

 

 浏览http://localhost:8161/admin/topics.jsp查看

 

启动消费者

 

 浏览http://localhost:8161/admin/topics.jsp查看

 

Guess you like

Origin www.cnblogs.com/wishsaber/p/12303308.html