activemq 收发消息

收:

package activemq.demo1;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Receiver implements MessageListener {
 @Override
 public void onMessage(Message message) {
  // TODO Auto-generated method stub
  if (message instanceof TextMessage) {
   try {
    System.out.println(((TextMessage) message).getText());
   } catch (JMSException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 public static void main(String[] args) {
  new Receiver().receiver();
 }

 public void receiver() {
  ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(
    "tcp://127.0.0.1:61616");
  try {
   QueueConnection queueConn = (QueueConnection) connFactory
     .createConnection();
   queueConn.start();
   QueueSession queueSession = queueConn.createQueueSession(false,
     Session.AUTO_ACKNOWLEDGE);
   Queue queue = queueSession.createQueue("queue/sendMsg");
   MessageConsumer consumer = queueSession.createConsumer(queue);
   consumer.setMessageListener(this);
   // TextMessage txtMsg = (TextMessage)consumer.receive();
   // System.out.println(txtMsg.getText());
//   consumer.close();
//   queueSession.close();
//   queueConn.close();
  } catch (JMSException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

 

发:

package activemq.demo1;

import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Send {
 public static void main(String[] args) {
  ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(
    "tcp://127.0.0.1:61616");
  try {
   QueueConnection queueConn = (QueueConnection) connFactory
     .createConnection();
   QueueSession queueSession = queueConn.createQueueSession(false,
     Session.AUTO_ACKNOWLEDGE);
   Queue queue = queueSession.createQueue("queue/sendMsg");
   MessageProducer producer = queueSession.createProducer(queue);
   producer.send(queueSession.createTextMessage("测试"));
   producer.close();
   queueSession.close();
   queueConn.close();
  } catch (JMSException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

阅读更多
想对作者说点什么? 我来说一句

Spring整合JMS——实现收发消息

2015年11月04日 12.38MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭