sub*_*bro 5 java activemq-classic jms producer-consumer
我试图在 Active MQ(版本 5.15.0)中创建消费者级别超时。考虑消费者选择了一条消息但无法确认,因此在这种情况下,我希望消费者超时,以便其他消费者可以选择收听经纪人的消息。
我的生产者代码在其中设置了两个消费者侦听器:
public class JmsMessageListenerAckExample {
public static void main(String[] args) throws URISyntaxException, Exception {
Connection connection = null;
try {
// Producer
ConnectionFactory factory = createActiveMQConnectionFactory();
connection = factory.createConnection();
Session session = connection.createSession(false,
Session.CLIENT_ACKNOWLEDGE);
Queue queue = session.createQueue("customerQueue");
String payload = "Important Task";
Message msg = session.createTextMessage(payload);
MessageProducer producer = session.createProducer(queue);
System.out.println("Sending text '" + payload + "'");
producer.send(msg);
// Consumer
MessageConsumer consumer1 = session.createConsumer(queue);
consumer1.setMessageListener(
new AckMessageListener(false, "consumer1"));
Thread.sleep(1000);
System.out.println("Creating new message listener to acknowledge");
producer.send(msg);
MessageConsumer consumer2 = session.createConsumer(queue);
consumer2.setMessageListener(
new AckMessageListener(true, "consumer2"));
connection.start();
Thread.sleep(3000);
session.close();
} finally {
if (connection != null) {
connection.close();
}
}
}
private static ActiveMQConnectionFactory createActiveMQConnectionFactory() {
// Create a connection factory.
final ActiveMQConnectionFactory connectionFactory =
new ActiveMQConnectionFactory("tcp://localhost:61616");
// Pass the username and password.
connectionFactory.setUserName("user");
connectionFactory.setPassword("user");
return connectionFactory;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的消费者听众:
public class AckMessageListener implements MessageListener {
private boolean acknowledge;
private String consumerName;
public AckMessageListener(boolean acknowledge, String consumerName) {
this.acknowledge = acknowledge;
this.consumerName = consumerName;
}
public void onMessage(Message message) {
boolean terminate = !acknowledge;
try {
System.out.println("ConsumerName="+consumerName+", Acknowledge="+acknowledge);
if (acknowledge) {
try {
message.acknowledge();
} catch (JMSException e1) {
e1.printStackTrace();
}
}
System.out.println(message);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (terminate) {
Thread.currentThread().interrupt();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想以一种consumer1侦听消息但不确认的方式进行模拟,以便它超时我正在尝试释放线程,我希望我consumer2能捡起它并确认消息,以便消息从“消息入队”中移出” 状态到“消息出队”状态,但我consumer2无法接收任何消息事件。
有什么我做错了。如何使用 Active MQ 实现消费者级别的超时?
小智 1
处理这个问题的一种方法是使用事务(http://activemq.apache.org/how-do-transactions-work.html)。成功时调用 commit(),失败时调用 rollback(),或者如果在调用 commit() 之前关闭会话,则将发生重新传递(http://activemq.apache.org/message-redelivery-and-dlq-handling)。 html)。
| 归档时间: |
|
| 查看次数: |
1814 次 |
| 最近记录: |