Realize remote communication and replication of RabbitMQ, which can be used on wide area network
1. Start two RabbitMQ nodes with Docker
docker run -d --name=rabbitmqa -p 5772:5672 -p 15772:15672 -e RABBITMQ_NODENAME=rabbitmqa -h rabbitmqa rabbitmq:3.6.9-management
docker run -d --name=rabbitmqb -p 5773:5672 -p 15773:15672 -e RABBITMQ_NODENAME=rabbitmqb -h rabbitmqb rabbitmq:3.6.9-management
2. Open the shovel plugin
docker exec rabbitmqa bash -c "rabbitmq-plugins enable rabbitmq_shovel"
docker exec rabbitmqa bash -c "rabbitmq-plugins enable rabbitmq_shovel_management"
docker exec rabbitmqb bash -c "rabbitmq-plugins enable rabbitmq_shovel"
docker exec rabbitmqb bash -c "rabbitmq-plugins enable rabbitmq_shovel_management"
3. Obtain the IPs of the two RabbitMQ nodes
docker inspect --format='{{ .NetworkSettings.IPAddress }}' rabbitmqa
docker inspect --format='{{ .NetworkSettings.IPAddress }}' rabbitmqb
4. Edit the rabbitmq.config file, in the attachment
5. Replace the rabbitmq.config file in the Docker container
Just replace the configuration file of the source node
docker cp /home/robbie/Downloads/rabbitmq.config 017bf80d9b22:/etc/rabbitmq/rabbitmq.config
6. Restart the docker container
docker restart rabbitmqa
docker restart rabbitmqb
On the RabbitMQ management page, you can see that the corresponding queue and exchange have been automatically created on the two nodes.
7. Create a consumer on the destinations RabbitMQ node (rabbitmqb)
public class Consumer { public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); connectionFactory.setPort(5773); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.basicConsume("warehouse_carpinteria",true,"order_processor",new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("Message is: " + new String(body)); // channel.basicAck(envelope.getDeliveryTag(),false); } }); } }
8. Create a producer on the source RabbitMQ node (rabbitmqa)
@Test public void producer() throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); connectionFactory.setPort(5772); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("incoming_orders","direct",true); channel.basicPublish("incoming_orders", "warehouse", null, "RabbitMQ shovel test...".getBytes()); channel.close(); connection.close(); }
Run the consumer first, and then execute the producer, you can refer to the book RabbitMQ in action.