This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

The guide knowledge


In our previous program, we connect to RabbitBIMq and send and receive messages through RabbitMQ by amqp-client using the RabbitMQ native API to connect to RabbitMQ, declare switches, send messages, etc. So what if I want to send a message to RabbitMQ Server in Spring? This is where we need to use RabbitTemplate.

✨RabbitTemplate is a RabbitMQ message template provided by the Spring-AMqp dependency. It has a mapping relationship with the RabbitMQ Server. We only need to configure RabbitTemplate. We can send data from our application to RabbitMQ Server.

RabbitTemplate provides the following functions: edit the message, send the message, listen before sending the message, ConfirmCallback after sending the message, ReturnCallback after sending the message, and so on. We just need to configure RabbitTemplate and instantiate it in the Spring container, so we can use it to do all kinds of things.

The RabbitMQ SpringtBoot integration

  1. Create a SpringBoot project and introduce the RabbitMQ dependencies
Copy the code
  1. configurationapplication.ymlThe configuration file
RabbitMq: host: Port: 5672 username: admin Password: admin Virtual-host: > > < span style = "font-size: 14px; font-size: 14px! Important;" acknowledge-mode: manualCopy the code
  1. Custom message acknowledgement and failure callbacks
  • Message acknowledgement callback, which is called when a message arrives at the Broker
@Component public class MyConfirmCallback implements RabbitTemplate.ConfirmCallback { @Override public void Confirm (CorrelationData CorrelationData, Boolean ack, String s) {if(ack){system.out.println (" Successfully sent "); }else{system.out.println (" failed to post "); }}}Copy the code
  • Message failure callback, such as when the switch cannot route a message to a specified queue
@Component public class MyReturnCallback implements RabbitTemplate.ReturnCallback { @Override public void Return Message(Message Message, int I, String s, String s1, String s2) {system.out.println (" Message Posting error callback "); }}Copy the code
  1. Create a configuration class RabbitMQConfig, define Exchange and Queue, bind the Queue to the switch, and configure the RabbitTemplate message template.
@Configuration public class RabbitMQConfig { private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class); @Resource private MyConfirmCallback confirmCallback; @Resource private MyReturnCallback returnCallback; @autowired private CachingConnectionFactory CachingConnectionFactory; // Configure the RabbitTemplate message template. @bean public RabbitTemplate RabbitTemplate () {RabbitTemplate RabbitTemplate = new RabbitTemplate(cachingConnectionFactory); / / message delivery success callback rabbitTemplate setConfirmCallback (confirmCallback); . / / the message delivery failure callback rabbitTemplate setReturnCallback (returnCallback); return rabbitTemplate; } /** * declare Queue * @return */ @bean public Queue() {return new Queue("queue4"); Public DirectExchange DirectExchange() {return new DirectExchange("Direct"); } @bean public Binding bingding() {return bindingBuilder.bind (queue()). To (directExchange()). with("springboot"); }}Copy the code
  1. Producer sends message
@RunWith(SpringRunner.class) @SpringBootTest class RabbitmqApplicationTests { @Resource private RabbitTemplate rabbitTemplate; @ Test void contextLoads () {/ / messaging rabbitTemplate convertAndSend (" Direct ", "springboot", "the Programmer do not drink milk tea"); }}Copy the code
  1. The consumer listens to the queue and consumes the message
@Component public class Comsummer { @RabbitListener(queues = "queue4") public void receiverMessage(Object msg, Throws IOException {system.out.println (" received Message: "+ MSG); / / manual ACK channel. BasicAck (message. GetMessageProperties () getDeliveryTag (), false); }}Copy the code

Extension: With the method of the configuration class for switches, and switches and queue queue statement binding (notes) (in the actual production environment, on the producer side for binding or binding on the consumer can be, but binding on consumers will be better, because we consumers is the first start up service, if the queue is not a statement, There will be a start error on the consumer side, so it is better to bind the switch to the queue when the consumer starts.

For example, a switch and queue can be declared and bound to a queue as follows:

Component @RabbitListener(bindings = @QueueBinding( value=@Queue(value = "queue4",durable = "false",autoDelete = "false"), exchange=@Exchange(value = "Direct",type = ExchangeTypes.DIRECT), key = "springboot" )) public class Comsummer { @RabbitHandler public void receiverMessage(Object msg, Throws IOException {system.out.println (" received Message: "+ MSG); channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); }}Copy the code

🏁 This is a brief introduction to the process of integrating Spring Boot into RabbitMQ. If there are any bugs, please leave a comment to correct them. If you find this article helpful, please click 👍 😋😻😍 k3u1fbpfcp-watermark.image)