我正在使用Eclipse,Tomcat和Rabbit MQ。
我希望能够在队列中消息后立即使用队列消息。我已经设法在Eclipse中使用Java类(见下文),但在Tomcat服务器上部署WAR文件时无法实现这一点。
package org.com.hello;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
public class HelloRecv {
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("172.24.3.53");
factory.setPort(6672);
factory.setUsername("user");
factory.setPassword("password");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("q1", true, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume("q1", true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
我是否需要像web.xml文件一样添加内容,如果有,我应该将哪些内容添加到此文件中?
答案 0 :(得分:0)
使用eclipse创建一个war应用程序:
你可以看到这个视频: https://www.youtube.com/watch?v=fk22hQz9L_M
或谷歌搜索然后将您的代码复制到servlet中。您应该使用init方法。
伪代码:
public class YourServlet extends HttpServlet {
int count;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("172.24.3.53");
factory.setPort(6672);
factory.setUsername("user");
factory.setPassword("password");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("q1", true, false, false, null);
/// you shoud put the consumer inside a thread.
channel.basicConsume("q1", true, new DefaultConsumer(){
/// here you should use Default consumer and not QueueingConsumer because is blocking
});
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
.....
}
}
希望有所帮助