消息隊列-ActiveMQ P2P模式

1.導依賴包

<dependency>
  <groupId>org.apache.activemq</groupId>
   <artifactId>activemq-all</artifactId>
   <version>5.15.10</version>
</dependency>

2.消息生產者

public class Sender {

    public static void main(String[] args) throws JMSException, InterruptedException {
        // 1. 建立工廠對象
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_BROKER_URL,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://localhost:61616");
        //2. 從工廠裏獲取一個連接
        Connection connection = factory.createConnection();
        connection.start();
        //3. 從連接中獲取Session(會話)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4. 從會話中獲取目的地(Destination),消費者會從這個目的地取消息
        Queue queue = session.createQueue("lance");
        //5. 從會話中創建消息提供者
        MessageProducer producer = session.createProducer(queue);
        int i = 1;
        try {
            while (true) {
                //從會話中創建文本消息(也可以創建其它類型的消息體)
                TextMessage textMessage = session.createTextMessage("hello" + i);
                Thread.sleep(1000);
                // 通過消息提供者發送消息到ActiveMQ
                producer.send(textMessage);
                i++;
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 關閉連接
            connection.close();
        }
        System.out.println("exit");

    }
}

3.消息消費者

public class Recviver {

    public static void main(String[] args) throws JMSException {
        // 1. 建立工廠對象
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_BROKER_URL,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://localhost:61616");
        //2. 從工廠裏獲取一個連接
        Connection connection = factory.createConnection();
        connection.start();
        //3. 從連接中獲取Session(會話)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4. 從會話中獲取目的地(Destination),消費者會從這個目的地取消息
        Destination destination = session.createQueue("lance");
        //5. 從會話中創建消息消費者
        MessageConsumer consumer = session.createConsumer(destination);

        //6. 持續的消費
        try {
            while (true) {
                TextMessage textMessage = (TextMessage) consumer.receive();
                System.out.println("消費:" + textMessage.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉連接
            connection.close();
        }


    }
}

發佈了41 篇原創文章 · 獲贊 13 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章