目录
1.pom.xml
org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-starter-test
2.启动类
@SpringBootApplication public class ProducerApplication { public static void main(String[] args) { SpringApplication.run(ProducerApplication.class); } }
3.application.yml:ip、端口、username、password、虚拟主机
#配置rabbitmq的基本信息,ip\端口\username\password\虚拟机 spring: rabbitmq: host: 172.16.98.13 port: 5672 username: guest password: guest virtual-host: /
4.配置类:RabbitMQConfig:交换机、队列、他们的关系(rount key)
@Configuration public class RabbitMQConfig { public static final String EXCHAGE_NAME = "boot_topic_exchange"; public static final String QUEUE_NAME = "boot_queue"; // 1.交换机 @Bean("bootExchange") public Exchange bootExchange(){ return ExchangeBuilder.topicExchange(EXCHAGE_NAME).durable(true).build(); } // 2.Queue队列 @Bean("bootQueue") public Queue bootQueue(){ return QueueBuilder.durable(QUEUE_NAME).build(); } // 3.队列和交换机绑定关系Bingding /** * 1.知道哪个队列 * 2.知道哪个交换机 * 3.routting key */ @Bean public Binding bingQueueExchange(@Qualifier("bootQueue")Queue queue,@Qualifier("bootExchange")Exchange exchange){ return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs(); } }
5.发送消息
@SpringBootTest @RunWith(SpringRunner.class) public class ProducerTest { // 1.注入springTemplate @Autowired private RabbitTemplate rabbitTemplate; @Test public void testSend(){ rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHAGE_NAME,"boot.haha","boot mq hello..."); }
1.pom.xml
org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-starter-test
2.启动类
@SpringBootApplication public class ConsumerSpringbootApplication { public static void main(String[] args) { SpringApplication.run(ConsumerSpringbootApplication.class); } }
3.application.yml:ip、端口、username、password、虚拟主机
#配置rabbitmq的基本信息,ip\端口\username\password\虚拟机 spring: rabbitmq: host: 172.16.98.13 port: 5672 username: guest password: guest virtual-host: /
4.消息监听
@Component public class RabbitMQListener { @RabbitListener(queues = "boot_queue")//监听队列的名称 public void ListenerQueue(Message message){//将来如果有消息会封装在message中,不要导错包core核心包中 System.out.println(message.getBody());//获取消息体,消息体才是有用内容 } }
confims模式