1. 程式人生 > >activemq 學習系列(四) 訊息提供和消費

activemq 學習系列(四) 訊息提供和消費

訊息提供和消費

 

package com.test;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ActiveMqTest { public static void main (String[] args) { producer(); // consumer(); } public static void producer () { try { String brokerURL = "tcp://localhost:61616"; String user = "admin"; String password = "admin
"; ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, brokerURL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination queue
= session.createQueue("demoQueue"); MessageProducer messageProducer = session.createProducer(queue); messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); String text = "hello activemq"; Message textMessage = session.createTextMessage(text); messageProducer.send(textMessage); session.close(); connection.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } public static void consumer () { try { String brokerURL = "tcp://localhost:61616"; String user = "admin"; String password = "admin"; ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, brokerURL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination queue = session.createQueue("demoQueue"); MessageConsumer consumer = session.createConsumer(queue); Message message = consumer.receive(1000); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); System.out.println( text ); } consumer.close(); session.close(); connection.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }

1、執行 producer 方法後在管理介面可以看到相關資訊

2、執行 consumer 方法,消費訊息