This is the 28th day of my participation in Gwen Challenge

Accumulate over a long period, constant dripping wears away a stone 😄

The Return mechanism

In the previous article, we covered the sender confirmation mechanism, which confirms that a producer successfully sent a message to the switch. Whether the switch sends messages to a specific queue is unknown. If you want to know whether the switch successfully sent a message to the queue, you need to use the return mechanism to monitor whether the switch sent a message to the queue.

The callback interface ReturnListener can be added to the addReturnListener method provided in the client Channel interface. The ReturnListener interface contains a method: HandleReturn, which handles the failure of the switch to send a message to the queue.

Native API approach

// omit get connection, get channel
String quequ = "queue-2";
String exchange = "exchange-2";
String key = "key-2";
// Create a switch
channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC, true);
// Create a queue
channel.queueDeclare(quequ, true.false.false.null);
// The queue is bound to the switch
channel.queueBind(quequ, exchange, key);
// Enable the message confirmation mechanism
channel.confirmSelect();
channel.addConfirmListener(new ConfirmListener() {
    // Parameter 1: deliveryTag: number of the message
    // Multiple: whether to batch confirm true Yes
    public void handleAck(long deliveryTag, boolean multiple) throws IOException {
        System.out.println("Message sent to switch successful,deliveryTag:" + deliveryTag + ", multiple: " + multiple);
    }

    public void handleNack(long deliveryTag, boolean multiple) throws IOException {
        System.out.println("Message sent to switch failed, deliveryTag:" + deliveryTag + ", multiple: "+ multiple); }});/ / Return mechanism
channel.addReturnListener(new ReturnListener() {
    /* * Parameter 1: response code * parameter 2: response text * Parameter 3: switch name * Parameter 4: route key * parameter 5: basic attribute set of the message * Parameter 6: message content */
    public void handleReturn(int replyCode, String replyText,
                             String exchange, String routingKey,
                             AMQP.BasicProperties properties, byte[] body) throws IOException {
        // This is where the callback after basic. Return is executed
        // Execute this method if the switch fails to send a message to the queue
        System.out.println("replyCode =" + replyCode);
        System.out.println("replyText =" + replyText);
        System.out.println("exchange =" + exchange);
        System.out.println("routingKey =" + routingKey);
        System.out.println("properties =" + properties);
        System.out.println("body =" + newString(body)); }});/** * Third parameter: mandatory: When the mandatory parameter is set to true and * the switch cannot find a queue that matches its type and routing key, * RabbitMQ calls basic. Return to Return the message to the producer. * When the mandatory parameter is set to false, the message is discarded. * /
String message = "Send route key =" + key +"The news";
channel.basicPublish(exchange, key,true.null,message.getBytes());
System.out.println("Other logic");
Copy the code

Start themainThe console prints the following:Then we willThe value of the property keyModified tokey-2222To comment outCreate switches, create queues, and bind queues to switchesThe code. Start themainThe console prints the following:According to the log, the message is successfully sent to the switch but not to the specified queue because the corresponding queue cannot be matched according to the route key.

Note: When channel.basicPublish is called, the mandatory parameter is set to true

Of course you can test itmandatoryParameters forfalseWhen. channel.basicPublish(exchange, key,false, null,message.getBytes()); You can see that the result is not executedhandleReturnCallback function.

The Boot mode

Enable the Return mechanism in YML

spring:
  application:
    name: info-config-boot
  rabbitmq:
    host: 47.105. *
    port: 5672
    virtual-host: /test-1
    username: *
    password: *
    # Enable Return
    publisher-returns: true

Copy the code

coding

Create the class and implement the ReturnCallback interface

@Component
public class Return implements RabbitTemplate.ReturnCallback {

    Logger logger = LoggerFactory.getLogger(Return.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /** * The ConfirmCallback method will not be invoked unless the ConfirmCallback value is assigned to the ConfirmCallback. The default is null */
    @PostConstruct
    public void init(a){
        rabbitTemplate.setReturnCallback(this);
    }
    // The switch fails to send a message to the queue.
    @Override
    public void returnedMessage(Message message,
                                int replyCode, String replyText,
                                String exchange, String routingKey) {
        logger.info("Switch fails to send message to queue =====");
        logger.info("message = {}".new String(message.getBody()));
        logger.info("replyCode = {}",replyCode);
        logger.info("replyText = {}",replyText);
        logger.info("exchange = {}",exchange);
        logger.info("routingKey = {}",routingKey); }}Copy the code

Provides external call methods

@Autowired
RabbitTemplate rabbitTemplate;

@GetMapping("/send")
public void send(String exchange,String key){
    CorrelationData correlation = new CorrelationData("Setup:" + UUID.randomUUID().toString());
    rabbitTemplate.convertAndSend(exchange,key,"Send message",correlation);
}
Copy the code

The send method has two new input parameters that dynamically control the switch and routing key names. Exchange-1 and key-1 already exist.

Call interface:http://localhost:8080/send?exchange=exchange-1&key=key-1. Switches and routing keys exist.Call interface:http://localhost:8080/send?exchange=exchange-1&key=key-155. The switch exists, but the routing key does not exist.

He drew a reluctant picture.

At this point, a message is actually sent to the specified queue.

  • If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please like it and follow it.