为消息保持JMS使用者的活动状态



我正在编写一个简单的java程序,用于创建JMSConsumer。我希望消费者等到生产者发布了一些东西,然后主程序也被终止。这是我的主要:

JMSContext context;
Destination destination; 
JMSConsumer consumer;

JmsConnectionFactory connectionFactory = createJMSConnectionFactory();
setJMSProperties(connectionFactory);
System.out.println("MQ Test: Connecting to " + HOST + ", Port " + PORT + ", Channel " + CHANNEL
+ ", Connecting to " + QUEUE_NAME);
try {
context = connectionFactory.createContext(); 
destination = context.createQueue("queue:///" + QUEUE_NAME); 
consumer = context.createConsumer(destination); 
MessageListener ml = new DemoMessageListener(); 
consumer.setMessageListener(ml); 

System.out.println("The message listener is running."); // (Because the connection is started by default)
context.start();


} catch (Exception e){}

问题是,当程序到达主程序的底部时,程序就结束了
我试图获得的结果类似于RabbitMq的basicConsuime(下面的例子(:

public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "");
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
}

当main结束时,读取消息的线程仍然处于活动状态,并且每次向队列发送消息时都会调用deliveryCallback。


有什么想法吗?

在当前情况下,只要主进程结束,进程就会被终止,所有与进程关联的线程也会被终止。

有几个选项可以实现您提到的目标。

  1. 您可以将代码部署在任何像tomcat这样的容器中作为应用程序这将保持进程运行
  2. 另一种方法是让主线程忙于等待,并在需要时使用thread.notify终止

好吧,如果你只想做与你的"基本消费"相同的事情,你可以这样做(忘记你的Demo监听器等(:

...
try {
context = connectionFactory.createContext(); 
destination = context.createQueue("queue:///" + QUEUE_NAME); 
consumer = context.createConsumer(destination); 
/*
MessageListener ml = new DemoMessageListener(); 
consumer.setMessageListener(ml); 

System.out.println("The message listener is running."); // (Because the connection is started by default)
context.start();
*/

String  body = consumer.receiveBody(String.class);
System.out.println("Received message body: " + body);

} catch (Exception e){}

最新更新