1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
2.配置properties
spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=admin
3.定义RabbitConfig
package com.example.sendmsg; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { @Bean public Queue queue(){ return new Queue("ch1");//定义队列 } }
4.定义消息接收方法
package com.example.sendmsg; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.io.IOException; @Component public class MQReceiver { @RabbitListener(queues = "ch1",ackMode = "MANUAL")//手动应答 @RabbitHandler public void recv(Message msg, Channel channel) throws IOException, InterruptedException { System.out.println("recv1 msg:"+msg.getMessageProperties().getDeliveryTag()+" "+new String(msg.getBody())); channel.basicAck(msg.getMessageProperties().getDeliveryTag(),true); } @RabbitListener(queues = "ch1",ackMode = "AUTO")//自动应答 @RabbitHandler public void recv2(Message msg, Channel channel) throws IOException, InterruptedException { System.out.println("recv2 msg:"+msg.getMessageProperties().getDeliveryTag()+" "+new String(msg.getBody())); } }
5.定义消息发送方法
package com.example.sendmsg.controller; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; @Controller public class SendController { @Resource private AmqpTemplate amqpTemplate; @GetMapping("/testsend") @ResponseBody public String testSend(){ amqpTemplate.convertAndSend("ch1","hello mq"); return "send ok"; } }