如何在 activemq artemis 中从失败的事务中恢复消息

问题描述 投票:0回答:0
val connectionFactory = ActiveMQConnectionFactory(url)
val connection = connectionFactory.createConnection()
val session = connection.createSession(true, Session.SESSION_TRANSACTED)
val destination = session.createQueue("example.queue")

val producer = session.createProducer(destination)

// Maintain a list of messages sent within the transaction
val messagesInTransaction = mutableListOf<Message>()

// Send a batch of messages within a transaction
val numMessagesToSend = 10
for (i in 1..numMessagesToSend) {
    val message = session.createTextMessage("Hello, World! ($i)")
    producer.send(message)
    messagesInTransaction.add(message)
}

// Commit the transaction
try {
    session.commit()
    println("Transaction committed successfully")
} catch (e: Exception) {
    // Roll back the transaction and retry sending the messages
    session.rollback()
    println("Transaction rolled back: $e")
    
    for (message in messagesInTransaction) {
        println("Retrying sending message: $message")
        producer.send(message)
    }
}

// Close the JMS resources
producer.close()
session.close()
connection.close()

我发现这个 kotlin 代码使用 List 获取事务中的所有消息,如果提交失败并且我们转到 catch 块,我们使用该列表作为失败事务的恢复消息并再次发送它们。 这是从失败的交易中恢复消息的最佳实践吗?

我还看了一篇关于回滚方法的文章说,当事务失败时,消息存储在发送者的消息缓冲区中。为何如此 ?你能给我一个恢复消息缓冲区的例子吗?

kotlin activemq activemq-artemis
© www.soinside.com 2019 - 2024. All rights reserved.