【发布时间】:2012-01-24 20:22:30
【问题描述】:
我有一个长期订阅者的主题。我可以发布和使用消息,但是我发现从主题中读取消息时存在一些延迟。
我无法在一次通话中阅读这些消息。我需要多次调用该方法来阅读消息。我错过了什么吗?
private void publishMessage() {
TopicConnection topicConnection = null;
TopicSession topicSession = null;
TopicPublisher topicPublisher = null;
try {
topicConnection = connectionFactory.createTopicConnection();
topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
Topic topicName= topicSession.createTopic(topicName);
topicPublisher = topicSession.createPublisher(topicName);
ObjectMessage message = topicSession.createObjectMessage(customObject)
message.setStringProperty("user", userProperty);
topicPublisher.publish(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, timeToLive);
} catch (JMSException e) {
throw new RuntimeException("Error Sending UMessage", e);
} finally {
closeConnections(null, topicPublisher, topicSession, topicConnection);
}
}
public void consumeMessages(String userId, int maxResults) {
TopicConnection topicConnection = null;
TopicSession topicSession = null;
TopicSubscriber topicSubscriber = null;
try {
topicConnection = connectionFactory.createTopicConnection("guest","guest");
topicConnection.setClientID("topic");
topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
Topic topicName= topicSession.createTopic(topicName);
topicSubscriber = topicSession.createDurableSubscriber(topicName, "subscriptionname", String.format("user = '%s'", userName), false);
topicConnection.start();
Message msg = null;
do {
msg = topicSubscriber.receiveNoWait();
if (msg instanceof ObjectMessage) {
ObjectMessage om = (ObjectMessage) msg;
else {
log.error(String.format(" %s", om.getObject().getClass().getSimpleName()));
}
} else if (msg != null) {
log.error(String.format("e %s", msg.getClass().getSimpleName()));
}
} while (msg != null && out.size() <= maxResults);
} catch (JMSException e) {
throw new RuntimeException("Error retrieving User Messages", e);
} finally {
closeConnections(topicSubscriber, null, topicSession, topicConnection);
}
return out;
}
【问题讨论】: