大家好,我无法使用活动 mq 接收异步消息,下面是我用于发布消息和订阅的代码。
public class publishMessage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InitialContext initCtx = new InitialContext();
Context envContext = (Context) initCtx.lookup("java:comp/env");
ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) envContext.lookup("jms/ConnectionFactory");
Connection connection = connectionFactory.createConnection();
connection.start() ;
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("jms/topic/MyQueue");
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT) ;
TextMessage msg=session.createTextMessage();
msg.setText("Message sent");
System.out.println("Message Sent");
producer.send(msg);
session.commit() ;
connection.close() ;
}catch(Exception ex){
ex.printStackTrace() ;
}
}}
class Consumer{
protected Queue queue;
protected String queueName = "jms/topic/MyQueue";
protected String url = ActiveMQConnection.DEFAULT_BROKER_URL;
protected int ackMode = Session.AUTO_ACKNOWLEDGE;
public static void main(String[] args) {
Consumer rec=new Consumer();
try {
rec.run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() throws JMSException{
System.out.println("URL:" + url);
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
TopicConnection connection = (TopicConnection)connectionFactory.createTopicConnection();
connection.setClientID("Testingconn1") ;
connection.start();
MessageConsumer consumer = null;
Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
queue = session.createQueue(queueName) ;
consumer = session.createConsumer(queue);
consumer.setMessageListener(new MyListener()) ;
session.commit() ;
consumer.close();
session.close();
connection.close();
}
}
package com.java;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class MyListener implements MessageListener{
@Override
public void onMessage( final Message message )
{
if ( message instanceof TextMessage )
{
final TextMessage textMessage = (TextMessage) message;
try
{
System.out.println("Listener:" + textMessage.getText() );
}
catch (final JMSException e)
{
e.printStackTrace();
}
}
}
}
当我执行上述代码时,发布者成功发送了一条消息,当我启动消费者时,输出按要求出现,没有输出进入我的控制台。
请帮我解决它或建议一个代码来接收异步消息。