您好我创建了以下类来从jibco jms队列中读取消息。在另一个类中,我创建了这个类的一个实例,并尝试将getMessage()放入一个搅拌器中。我在队列中放了一条消息,我的应用程序因为调用getMessage()方法而卡住......有什么想法吗?或者我可以在课堂上添加一些改进?
public class EMSReceiver {
private QueueConnection connection;
private QueueReceiver queueReceiver;
private Queue queue;
private TextMessage message;
public EMSReceiver(String initialContextFactory, String userName, String password, String serverUrl, String confact, String q){
try {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.PROVIDER_URL, serverUrl);
InitialContext jndi = new InitialContext(env);
QueueConnectionFactory connectionFactory = (QueueConnectionFactory) jndi.lookup(confact);
QueueConnection connection = connectionFactory.createQueueConnection(userName, password);
QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
this.queue = (Queue) jndi.lookup(q);
this.queueReceiver = session.createReceiver(queue);
connection.start();
}
catch (JMSException e) {
e.printStackTrace();
System.exit(0);
} catch (NamingException e) {
e.printStackTrace();
}
}
public String getMessage() throws JMSException{
try {
this.message = (TextMessage) queueReceiver.receive();
} catch (JMSException e) {
System.out.println("Could not retrieve the message.");
e.printStackTrace();
}
return message.getText();
}
答案 0 :(得分:2)
queueReceiver.receive()
方法将等待,直到它在队列中收到消息。如果您不想等,请使用receiveNoWait()
或receive(long timeout)
。可以在此处找到相关文档:https://javaee-spec.java.net/nonav/javadocs/javax/jms/QueueReceiver.html。