skip to content
Alvin Lucillo

Publishing to an exchange

/ 1 min read

Publishing to an exchange allows publishers to publish messages to different queues based on the routing key. In the example below, greetingsv2 queue is bound to events exchange via a binding with routing key events.hello. This means when a message is published with events and events.hello as the specified exchange and routing key respectively, the message will be routed to the destination (in this case, the greetingsv2 queue).

  rabbitmq docker exec -it rabbitmq rabbitmqadmin declare queue --name=greetingsv2
  rabbitmq docker exec -it rabbitmq rabbitmqadmin declare exchange --name=events --type=direct
  rabbitmq docker exec -it rabbitmq rabbitmqadmin declare binding --source=events --destination=greetingsv2 --routing-key=events.hello --destination-type=queue
  rabbitmq docker exec -it rabbitmq rabbitmqadmin get messages --queue=greetingsv2
┌───────────────┬─────────────┬──────────┬─────────────┬───────────────┬────────────┬─────────┬──────────────────┐
 payload_bytes redelivered exchange routing_key message_count properties payload payload_encoding
└───────────────┴─────────────┴──────────┴─────────────┴───────────────┴────────────┴─────────┴──────────────────┘
  rabbitmq docker exec -it rabbitmq rabbitmqadmin publish message --routing-key=events.hello --payload=henlo --exchange=events
Message published and routed successfully
  rabbitmq docker exec -it rabbitmq rabbitmqadmin get messages --queue=greetingsv2 
┌───────────────┬─────────────┬──────────┬──────────────┬───────────────┬────────────┬─────────┬──────────────────┐
 payload_bytes redelivered exchange routing_key message_count properties payload payload_encoding
├───────────────┼─────────────┼──────────┼──────────────┼───────────────┼────────────┼─────────┼──────────────────┤
 5 false events events.hello 0 henlo string
└───────────────┴─────────────┴──────────┴──────────────┴───────────────┴────────────┴─────────┴──────────────────┘