ActiveMQ--Queue模式

ActiveMQ是幹什麼的?

Queue模式

簡單demo

下載ActiveMQ,並運行 ActiveMQ Getting Started

說明 activemq-all的jar包需要使用jdk1.8

pom.xml

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.15.0</version>
</dependency>
package com.pgy.jms.p2p;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Date: Created in 27/12/2017 2:19 PM
 * @Author: pengganyu
 * @Desc:
 */

public class Cousmer {

    public static void main(String[] args) throws JMSException {
        ConnectionFactory factory = new ActiveMQConnectionFactory(
            ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD,
            ActiveMQConnectionFactory.DEFAULT_BROKER_URL);

        Connection connection = factory.createConnection();
        connection.start();//若connection不啓動,不會進行連接消費

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Queue queue = session.createQueue("hello");

        MessageConsumer consumer = session.createConsumer(queue);

        //        consumer.setMessageListener(message -> System.out.println(message));

        while (true) {
            TextMessage textMessage = (TextMessage) consumer.receive();

            System.out.println(textMessage);

        }

    }
}
package com.pgy.jms.p2p;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Date: Created in 27/12/2017 1:01 PM
 * @Author: pengganyu
 * @Desc:
 */

public class Producer {

    public static void main(String[] args) throws JMSException {
        ConnectionFactory factory = new ActiveMQConnectionFactory(
            ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD,
            ActiveMQConnectionFactory.DEFAULT_BROKER_URL);

        Connection connection = factory.createConnection();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Queue queue = session.createQueue("hello");

        MessageProducer producer = session.createProducer(queue);

        for (int i = 0; i < 100; i++) {
            TextMessage tx = session.createTextMessage("hello" + i);
            producer.send(tx);
        }

        connection.close();

    }
}

說明

  • 當生產者生產消息時,沒有consumer連接時,消息直接廢棄
  • consumer類當中,若Connection若未start,則不會得到消息
  • 當生產者生產消息時,若有n個consumer連接時,消息被平均分配到每一個consumer裏面,即每個consumer接收到 sum(message)/n

另一個demo

消費者

package com.pgy.mq;

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

import javax.jms.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by admin on 25/07/2017.
 */
public class Consumer {
    private static String        USER_NAME   = ActiveMQConnection.DEFAULT_USER;

    private static String        PASSWORD    = ActiveMQConnection.DEFAULT_PASSWORD;

    private static String        BROKEN_URL  = ActiveMQConnection.DEFAULT_BROKER_URL;

    AtomicInteger                count       = new AtomicInteger(0);

    ActiveMQConnectionFactory    connectionFactory;

    Connection                   connection;

    Session                      session;

    ThreadLocal<MessageConsumer> threadLocal = new ThreadLocal();

    public void init() {
        try {
            connectionFactory = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, BROKEN_URL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void getMessage(String disName) {
        Queue queue = null;
        try {
            queue = session.createQueue(disName);
            MessageConsumer messageConsumer = null;

            if (threadLocal.get() != null) {
                messageConsumer = threadLocal.get();
            } else {
                messageConsumer = session.createConsumer(queue);

                threadLocal.set(messageConsumer);
            }

            while (true) {
                Thread.sleep(1000);

                TextMessage textMessage = (TextMessage) messageConsumer.receive();

                if (textMessage != null) {
                    textMessage.acknowledge();

                    System.out.println(Thread.currentThread().getName() + "獲取消息:"
                                       + textMessage.getText() + "-----" + count.getAndIncrement());
                } else {
                    break;
                }

            }
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

生產者

package com.pgy.mq;

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

import javax.jms.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by admin on 25/07/2017.
 */
public class Producter {

    private static String            USER_NAME   = ActiveMQConnection.DEFAULT_USER;

    private static String            PASSWORD    = ActiveMQConnection.DEFAULT_PASSWORD;

    private static String            BROKEN_URL  = ActiveMQConnection.DEFAULT_BROKER_URL;

    static AtomicInteger             count       = new AtomicInteger(0);

    static ActiveMQConnectionFactory connectionFactory;

    static Connection                connection;

    static Session                   session;

    static ThreadLocal<MessageProducer>     threadLocal = new ThreadLocal();

    public static void main(String[] args) {
        init();
        sendMessage("hello");
    }

    public static void init() {

        try {
            connectionFactory = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, BROKEN_URL);
            connection = connectionFactory.createConnection();

            connection.start();

            session = connection.createSession(true, Session.SESSION_TRANSACTED);
        } catch (JMSException e) {
            e.printStackTrace();
        }

    }

    public static void sendMessage(String disName) {
        try {
            Queue queue = session.createQueue(disName);

            MessageProducer messageProducer = null;

            if (threadLocal.get() != null) {
                messageProducer = threadLocal.get();
            } else {
                messageProducer = session.createProducer(queue);

                threadLocal.set(messageProducer);
            }

            while (true) {
                Thread.sleep(10000);

                int sum = count.getAndIncrement();

                TextMessage textMessage = session.createTextMessage(
                    Thread.currentThread().getName() + "helloWorld, times = " + sum);

                messageProducer.send(textMessage);

                session.commit();
            }

        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

生產消息

package com.pgy.mq;

/**
 * Created by admin on 25/07/2017.
 */
public class TestMProducter {

    public static void main(String[] args) {

        Producter producter = new Producter();
        producter.init();

        TestMProducter testMProducter = new TestMProducter();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(testMProducter.new ProducterMq(producter)).start();
        new Thread(testMProducter.new ProducterMq(producter)).start();
        new Thread(testMProducter.new ProducterMq(producter)).start();
        new Thread(testMProducter.new ProducterMq(producter)).start();
        new Thread(testMProducter.new ProducterMq(producter)).start();

    }

    private class ProducterMq implements Runnable {
        Producter producter;

        public ProducterMq(Producter producter) {
            this.producter = producter;
        }

        @Override
        public void run() {
            while (true) {
                producter.sendMessage("pengganyu");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

消費消息

package com.pgy.mq;

/**
 * Created by admin on 01/08/2017.
 */
public class TestConsumer {

    public static void main(String[] args) {

        Consumer consumer = new Consumer();
        consumer.init();

        TestConsumer testMProducter = new TestConsumer();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(testMProducter.new ConsumerMq(consumer)).start();
        new Thread(testMProducter.new ConsumerMq(consumer)).start();
        new Thread(testMProducter.new ConsumerMq(consumer)).start();
        new Thread(testMProducter.new ConsumerMq(consumer)).start();
        new Thread(testMProducter.new ConsumerMq(consumer)).start();

    }

    private class ConsumerMq implements Runnable {
        Consumer consumer;

        public ConsumerMq(Consumer cosum) {
            this.consumer = cosum;
        }

        @Override
        public void run() {
            while (true) {
                consumer.getMessage("pengganyu");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

監控臺

  • 127.0.0.1:8161/admin
  • 跑一會生產消息後,控制檯的QUEU裏面會有消息的數量在增加
  • 關掉生產消息進程,此時的消息會被存放,等消費消息的代碼跑起來後,消息數量纔會減少
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章