1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package cn.devmgr.activemqlistener;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage;
public class JmsMessageReceiver {
public static void main(String[] argvs) throws Exception { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("print-queue"); MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener(new ConsumerMessageListener("print-queue")); connection.start();
Thread.sleep(60000); session.close();
connection.close(); }
public static class ConsumerMessageListener implements javax.jms.MessageListener { private String consumerName;
public ConsumerMessageListener(String consumerName) { this.consumerName = consumerName; }
public void onMessage(Message message) { TextMessage textMessage = (TextMessage) message; try { System.out.println(consumerName + " received " + textMessage.getText()); } catch (JMSException e) { e.printStackTrace(); } }
} }
|