Website address: www.rabbitmq.com/tutorials/t…
As shown, publisher P distributes messages to all queues through switch X, and each subscriber gets an equal amount of all messages. Simple and work queue modes do not care about the switch because there is only one queue between the publisher and subscriber. The publish-subscribe model has multiple queues, so you only need to introduce switches to distribute messages to queues. As shown in the sample code, the publisher needs to define the switch, and the subscriber binds his or her own queue to the publisher’s switch.
To avoid increasing the cost of understanding, the following sample code gives only “Hello World!” Minor changes in simple mode
producers
// Four parameters
// Exchange switch
// Queue name
// Set additional properties
// An array of message bytes passed
// Simple mode: The switch is empty with a queue name defined
// channel.basicPublish("", RabbitConstant.QUEUE_HELLOWORLD, null,message.getBytes());
// Pub/Sub mode: Switch mandatory, queue must be empty (queue defined by subscriber)
channel.basicPublish(RabbitConstant.EXCHANGE_WEATHER,"" , null , message.getBytes());
Copy the code
consumers
// queueBind is used to bind custom queues to switches
// Parameter 1: queue name Parameter 2: interactive machine name Parameter 3: route key (not used for publishing and subscribing)
channel.queueBind(RabbitConstant.QUEUE_BAIDU, RabbitConstant.EXCHANGE_WEATHER, "");
Copy the code
Defining a Switch
Publishers and subscribers are free to define queues, which can be created automatically when the RabbitMQ server does not have them, but switches need to create them manually. Log in to the RabbitMQ console and create the following:
Switch Type (Type) The value can be Direct or Fanout.