Rabbitmq basic introduction application

catalogue Fundamentals of Rabbitmq (I) introduction to Rabbitmq Rabbitmq Foundation (II) installation and configuration ...
catalogue
1. RabbitMQ working mode

1. RabbitMQ working mode

1.1 Work queues work queue mode and simple mode

1.1.1 mode description

  • Work Queues: compared with the simple mode of the entry program, there are one or more consumers, and multiple consumers consume messages in the same queue together. But the logic is the same.
  • Application scenario: in case of heavy tasks or more tasks, using work queue can improve the speed of task processing
1.1.2 code implementation

producer:

/** * send message */ public class Producer_HelloWorld { public static void main(String[] args) throws IOException, TimeoutException { //1. Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //2. Set parameters factory.setHost("192.168.1.1");//ip default value localhost factory.setPort(5672); //Port default 5672 factory.setVirtualHost("/demo");//Virtual machine defaults/ factory.setUsername("yy");//User name: default guest factory.setPassword("abc123");//Password default guest //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); //5. Create Queue /* queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) Parameters: 1. queue: Queue name 2. durable:Whether to persist or not, after mq is restarted, is still in use 3. exclusive: * Exclusive. Only one consumer can listen to this queue * Delete queue when Connection is closed * 4. autoDelete:Whether to delete automatically. When there is no Consumer, it will be deleted automatically 5. arguments: Parameters. */ //If there is no one named Hello_ If there is a queue in the world, the queue will be created. If there is, it will not be created channel.queueDeclare("hello_world",true,false,false,null); /* basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) Parameters: 1. exchange: Switch name. Exchange opportunities in simple mode use the default '' 2. routingKey: Route name 3. props: configuration information 4. body: Send message data */ String body = "hello rabbitmq~~~"; //6. Send message channel.basicPublish("","hello_world",null,body.getBytes()); //7. Release resources channel.close(); connection.close(); } }

consumer:
Omit redundant code

//The connection parameters are the same as above Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello_world",true,false,false,null); // receive messages Consumer consumer = new DefaultConsumer(channel){ /* Callback method, which will be executed automatically after receiving the message 1. consumerTag: identification 2. envelope: Get some information, switch, routing key 3. properties:configuration information 4. body: data */ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("body: "+new String(body)); } }; channel.basicConsume("hello_world",true,consumer); //Close resource? Don't always turn on the monitoring function because the consumer is a monitor

1.2 Pub/Sub subscription mode

1.2.1 mode description

In the subscription model, an Exchange role is added, and the process changes slightly:

  • P: The producer, that is, the program that sends the message, but it is no longer sent to the queue, but to X (switch)
  • C: The consumer, the receiver of the message, will always wait for the message to arrive
  • Queue: message queue, receiving messages and caching messages
  • Exchange: switch. On the one hand, it receives messages sent by producers. On the other hand, know how to process messages, such as submitting to a special queue
    Deliver to all queues, or discard messages. How to operate depends on the type of Exchange.
  • There are three common types of Exchange:
    ∙ Fanout: broadcast and deliver the message to all queues bound to the switch
    Direct: direct: send messages to the queue that matches the specified routing key
    Topic: wildcard, which gives the message to the queue conforming to the routing pattern
    Exchange (switch) is only responsible for forwarding messages and does not have the ability to store messages. Therefore, if no queue is bound to exchange or does not meet the requirements
    The queue of routing rules, then the message will be lost!

Code implementation:
producer:

//The connection parameters are the same as above //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); String exchangeName = "test_fanout"; //5. Create a switch channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null); //6. Create queue String queue1Name = "test_fanout_queue1"; String queue2Name = "test_fanout_queue2"; channel.queueDeclare(queue1Name,true,false,false,null); channel.queueDeclare(queue2Name,true,false,false,null); //7. Bind queue and switch /* queueBind(String queue, String exchange, String routingKey) Parameters: 1. queue: Queue name 2. exchange: Switch name 3. routingKey: Routing keys, binding rules If the switch type is fanout, routingKey is set to "" */ channel.queueBind(queue1Name,exchangeName,""); channel.queueBind(queue2Name,exchangeName,""); String body = "Log information: Zhang San called findAll method...Log level: info..."; //8. Send message channel.basicPublish(exchangeName,"",null,body.getBytes()); //9. Release resources channel.close(); connection.close();

consumer:
Multiple consumers are required. Only one is written here

//The connection parameters are the same as above //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); String queue1Name = "test_fanout_queue1"; String queue2Name = "test_fanout_queue2"; // receive messages Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("properties: "+properties);*/ System.out.println("body: "+new String(body)); System.out.println("Print log information to the console....."); } }; channel.basicConsume(queue1Name,true,consumer);

1.3 Routing mode

1.3.1 mode description

  • The binding between the queue and the switch cannot be arbitrary, but a routing key should be specified
  • When sending a message to Exchange, the sender of the message must also specify the RoutingKey of the message
  • Exchange will no longer deliver messages to each bound queue, but will judge according to the routing key of the message. Messages will be received only if the routing key of the queue is completely consistent with the routing key of the message
  • P: The producer sends messages to Exchange. When sending messages, a routing key will be specified
  • 10: Exchange (exchange) receives the producer's message, and then submits the message to the queue that exactly matches the routing key
  • C1: consumer, whose queue specifies the message whose routing key is error
  • C2: consumer, whose queue specifies the messages whose routing key needs to be info, error and warning
    producer:
//The connection parameters are the same as above //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); /* exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments) Parameters: 1. exchange:Switch name 2. type:Switch Type DIRECT("direct"),: directional FANOUT("fanout"),: Fan (broadcast), sending messages to each queue bound to it. TOPIC("topic"),Wildcard mode HEADERS("headers");Parameter matching 3. durable:Persistent 4. autoDelete:Auto delete 5. internal: Internal use. General false 6. arguments: parameter */ String exchangeName = "test_direct"; //5. Create a switch channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null); //6. Create queue String queue1Name = "test_direct_queue1"; String queue2Name = "test_direct_queue2"; channel.queueDeclare(queue1Name,true,false,false,null); channel.queueDeclare(queue2Name,true,false,false,null); //7. Bind queue and switch /* queueBind(String queue, String exchange, String routingKey) Parameters: 1. queue: Queue name 2. exchange: Switch name 3. routingKey: Routing keys, binding rules If the switch type is fanout, routingKey is set to "" */ //Queue 1 binding error channel.queueBind(queue1Name,exchangeName,"error"); //Queue 2 binding info error warning channel.queueBind(queue2Name,exchangeName,"info"); channel.queueBind(queue2Name,exchangeName,"error"); channel.queueBind(queue2Name,exchangeName,"warning"); String body = "Log information: Zhang San called delete method...Something went wrong... Log level: error..."; //8. Send message channel.basicPublish(exchangeName,"warning",null,body.getBytes()); //9. Release resources channel.close(); connection.close();

consumer:

//The connection parameters are the same as above //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); String queue1Name = "test_direct_queue1"; String queue2Name = "test_direct_queue2"; // receive messages Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("body: "+new String(body)); System.out.println("Print log information to the console....."); } }; channel.basicConsume(queue2Name,true,consumer);

1.4 Topics wildcard mode

1.4.1 mode description
  • Compared with Direct, Topic can route messages to different queues according to RoutingKey. However, Topic Exchange allows the queue to use wildcards when Binding routing keys!
  • Routingkey s are generally composed of one or more words, which are separated by ".", such as item.insert
  • Wildcard rule: # match one or more words, * match exactly one word, for example: item. # can match item.insert.abc or item.insert, and item. * can only match item.insert

  • Illustration:
    Red Queue: the bound is usa. #, so all routing key s starting with usa. will be matched
    Yellow Queue: bound to #. news, so all routing key s ending in. news will be matched
1.4.2 code implementation

producer:

//The setting parameters are the same as above Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); /* exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments) Parameters: 1. exchange:Switch name 2. type:Switch Type DIRECT("direct"),: directional FANOUT("fanout"),: Fan (broadcast), sending messages to each queue bound to it. TOPIC("topic"),Wildcard mode HEADERS("headers");Parameter matching 3. durable:Persistent 4. autoDelete:Auto delete 5. internal: Internal use. General false 6. arguments: parameter */ String exchangeName = "test_topic"; //5. Create a switch channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,false,false,null); //6. Create queue String queue1Name = "test_topic_queue1"; String queue2Name = "test_topic_queue2"; channel.queueDeclare(queue1Name,true,false,false,null); channel.queueDeclare(queue2Name,true,false,false,null); //7. Bind queue and switch /* queueBind(String queue, String exchange, String routingKey) Parameters: 1. queue: Queue name 2. exchange: Switch name 3. routingKey: Routing keys, binding rules If the switch type is fanout, routingKey is set to "" */ // routing key system name. Log level. //=Requirements: all error level logs are stored in the database, and all order system logs are stored in the database channel.queueBind(queue1Name,exchangeName,"#.error"); channel.queueBind(queue1Name,exchangeName,"order.*"); channel.queueBind(queue2Name,exchangeName,"*.*"); String body = "Log information: Zhang San called findAll method...Log level: info..."; //8. Send message channel.basicPublish(exchangeName,"goods.error",null,body.getBytes()); //9. Release resources channel.close(); connection.close();

consumer:

//The connection parameters are the same as above //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); String queue1Name = "test_topic_queue1"; String queue2Name = "test_topic_queue2"; // receive messages Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("body: "+new String(body)); System.out.println("Store log information in database......."); } }; channel.basicConsume(queue1Name,true,consumer);

If you like, please like it and collect it

17 November 2021, 22:05 | Views: 4167

Add new comment

For adding a comment, please log in
or create account

0 comments