据我所知,RabbitMQ不支持 XA 样式的事务。
是的,你可以用 Java 做到这一点:
测试配置.java
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.AbstractRabbitConfiguration;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.SingleConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfiguration extends AbstractRabbitConfiguration {
private String routingKey = "test.queue";
private String testQueueName = "test.queue";
public ConnectionFactory getConnectionFactory() {
SingleConnectionFactory connectionFactory = new SingleConnectionFactory("localhost");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
return connectionFactory;
}
@Override
public RabbitTemplate rabbitTemplate() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(getConnectionFactory());
rabbitTemplate.setRoutingKey(routingKey);
rabbitTemplate.setQueue(testQueueName);
return rabbitTemplate;
发送的简单示例:
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
public class MessageSender {
@Autowired
private AmqpTemplate template;
public void send(String text) {
template.convertAndSend(text);
}
}
..并接收:
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MessageHandler implements MessageListener {
@Override
public void onMessage(Message message) {
System.out.println("Received message: " + message);
}
}