您好我已将此WebListener类添加到我的webproject
@WebListener
public class SelfSend implements ServletContextListener {
private MessageProducer producer;
private Connection sendconnection;
private Connection receiveconnection;
private Session sendsession;
private Session receivesession;
private MessageConsumer receiver;
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
InitialContext initCtx = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory) initCtx.lookup("java:comp/env/jms/ConnectionFactory");
sendconnection = connectionFactory.createConnection();
receiveconnection = connectionFactory.createConnection();
sendsession = sendconnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
receivesession = receiveconnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = sendsession.createProducer((Destination) initCtx.lookup("java:comp/env/jms/queue/MyQueue"));
receiver = receivesession.createConsumer((Destination) initCtx.lookup("java:comp/env/jms/queue/MyQueue"));
receiver.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
System.out.println("MESSAGE RECEIVED");
}
});
TextMessage testMessage = sendsession.createTextMessage();
testMessage.setStringProperty("from", "ki");
producer.send(testMessage);
System.out.println("MESSAGE SENT");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
}
但是从未收到过该消息。
当我把reciver放在像这样的@WebServlet
时@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
InitialContext initCtx = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory) initCtx.lookup("java:comp/env/jms/ConnectionFactory");
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
receiver = session.createConsumer((Destination) initCtx.lookup("java:comp/env/jms/queue/MyQueue"));
receiver.setMessageListener(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
mud = new MongoUserdata();
}
我收到了这条消息,当我把它放入我只收到Servlet-Receiver的每一条消息时,另一个消息似乎丢失了。
有人能向我解释这种奇怪的行为吗?
答案 0 :(得分:0)
在您的第一个示例课程中,您似乎没有启动接收器连接,这意味着它不会发送任何收到的消息。然而,它将保留消费者预取缓冲区中的传入消息,从而导致您遇到的每个其他消息接收。