日期:2014-05-20  浏览次数:20687 次

关于activeMQ的消息监听
小弟最近在研究activeMQ~之前对于JMS也基本不太了解`~~

现在找了个简单的例子
代码中间有一段

  public void onMessage(Message message) {  
  try {  
  if (message instanceof TextMessage) {  
  TextMessage txtMsg = (TextMessage) message;  
  String msg = txtMsg.getText();  
  System.out.println("Consumer:->Received: " + msg);  
  } else {  
  System.out.println("Consumer:->Received: " + message); 
  }  
  } catch (JMSException e) {  
  // TODO Auto-generated catch block  
  e.printStackTrace();  
  }  
  }
这段应该是实现了监听消息的接口吧~
我想问的是,其中的message就是发送的消息,这段代码是在后台打印出消息内容来的..那我怎么在前台拿到这个message内容?
比如A给B发消息~B点接收后显示消息``

还有就是当A给B发送消息时,B是如何知道有没有消息增加?
我现在自己做一个小东西就是想要实现上面2个功能,A给B发消息后,B弹出提示或什么的,点接收就显示消息内容~

希望有心人能回答下~分不够可以加``

------解决方案--------------------
public void run() {
Connection connection = null;
try {
System.out.println("Connecting to URL: " + url);
System.out.println("Publishing a Message with size " + messageSize
+ " to " + (topic ? "topic" : "queue" + ": " + subject));
System.out.println("Using "
+ (persistent ? "persistent" : "non-persistent"
+ " messages"));
System.out.println("Sleeping between publish " + sleepTime + " ms");
if (timeToLive != 0) {
System.out.println("Messages time to live " + timeToLive
+ " ms");
}

// Create the connection.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
user, password, url);
//---------------------------------------


//-----------------------------------------

connection = connectionFactory.createConnection();
connection.start();

// Create the session
Session session = connection.createSession(transacted,
Session.AUTO_ACKNOWLEDGE);
//队列取数据========================================
//=================================================
if (topic) {
destination = session.createTopic(subject);
} else {
destination = session.createQueue(subject);
}

//QueueSession sessionQ =(QueueSession)connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//QueueReceiver receiver=sessionQ.createReceiver((Queue) destination);
// Create the producer.
MessageProducer producer = session.createProducer(destination);
/*
try{
TextMessage tm = (TextMessage) receiver.receive();
System.out.println("receive successful!");
String messageContent = tm.getText();
System.out.println("The content of the receiving message is:" + messageContent);

}catch(Exception ex){
ex.getStackTrace();
ex.getMessage();
}finally{
receiver.close();
}
*/
if (persistent) {
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
} else {
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
if (timeToLive != 0)
producer.setTimeToLive(timeToLive);

// Start sending messages
sendLoop(session, producer);

System.out.println("Done.");

// Use the ActiveMQConnection interface to dump the connection stats.
ActiveMQConnection c = (ActiveMQConnection) connection;