我有一个在远程机器 (JDK 1.6.0_30) 上运行的 Glassfish 3.1.2 服务器。以下代码是在 Java SE 环境中运行的独立客户端,使用 JNDI 查找连接到 JMS。客户端同时是发布者和订阅者。
我按如下方式创建了 JMS 连接池和主题:
./asadmin create-jms-resource --restype javax.jms.ConnectionFactory jms/TopicConnectionFactory
./asadmin create-jms-resource --restype javax.jms.Topic jms/TopicUpdate
我启动了这个客户端的两个实例。消息似乎已传递 - 没有错误 - 但消息没有到达订阅者......
我做错了什么?
感谢任何帮助 - 非常感谢!
public class JMS implements MessageListener {
private TopicConnectionFactory factory;
private TopicConnection connection;
private Topic topic;
private void subscribe() {
try {
System.setProperty("org.omg.CORBA.ORBInitialHost", "192.168.1.6");
System.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
InitialContext ctx = new InitialContext();
factory = (TopicConnectionFactory)ctx.lookup("jms/TopicConnectionFactory");
topic = (Topic)ctx.lookup("jms/TopicUpdate");
connection = factory.createTopicConnection();
TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = session.createSubscriber(topic);
subscriber.setMessageListener(this);
connection.start();
while(true) {
Thread.sleep(5000);
sendMessage();
}
} catch (InterruptedException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
} catch (JMSException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendMessage() {
try {
TopicSession session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = session.createPublisher(topic);
TextMessage message = session.createTextMessage();
message.setText("Message from client.");
publisher.send(message);
session.close();
System.out.println("Message sent.");
} catch (JMSException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void onMessage(Message msg) {
System.out.println("Message received.");
}
public JMS() {
subscribe();
}
public static void main(String[] args) {
new JMS();
}
}
最佳答案
当您在创建 session 时使用 true 作为第一个参数时,确认模式将被忽略并且您被假定为已被处理。尝试将第一个参数设为 false。
为了清楚起见,修改这行代码:
TopicSession session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
成为:
TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
在您的发送消息方法中。
关于java - Glassfish 和 JMS : Why do published messages not arrive at subscribers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10237400/