jms 订阅方式接收不到消息!!!!!!
发送消息没问题,就是同步接收不到!!!! 跪求大神 在线等
package com.fz.jms;
import java.util.Vector;
import javax.jms.*;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class TopicSubscribeSynchronous {
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private Topic topic = null;
private TopicConnection topicConnection = null;
private TopicSession topicSession = null;
private TopicSubscriber topicSubscriber = null;
//初始化
private void initialize(String groupName) throws JMSException, Exception {
//连接工厂是用户创建连接的对象,这里使用的是ActiveMQ的ActiveMQConnectionFactory根据url,username和password创建连接工厂。
ActiveMQConnectionFactory TopicConnectionFactory = new ActiveMQConnectionFactory(
user, password, url);
//连接工厂创建一个jms connection
topicConnection = TopicConnectionFactory.createTopicConnection();
//是生产和消费的一个单线程上下文。会话用于创建消息的生产者,消费者和消息。会话提供了一个事务性的上下文。
topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); //不支持事务
//目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象,两种消息传递方式:点对点和发布/订阅
topic = topicSession.createTopic(groupName);
//会话创建消息的生产者将消息发送到目的地
topicSubscriber = topicSession.createSubscriber(topic);
}
public Vector<String> subscriberMessage(String groupName) throws JMSException, Exception {
initialize(groupName);
topicConnection.start();
try {
// 开始监听
//consumer.setMessageListener(this);
Vector<String> v=new Vector<String>(10);
// for (int i=0; i<10; i++)
// {
//同步消息接收,使用receive方法,堵塞等待,直到接收消息
TextMessage txtMsg = (TextMessage) topicSubscriber.receive();
// if(txtMsg==null)
// {
// break;
// }else
// {
String msg = txtMsg.getText();
System.out.println(msg);
v.add(msg);
// }
// }
return v;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}finally
{
close();
}
}
// 关闭连接
public void close() throws JMSException {
if (topicSubscriber != null)
topicSubscriber.close();
if (topicSession != null)
topicSession.close();
if (topicConnection != null)
topicConnection.close();
}
}