RabbitMQ-SpringBoot整合RabbitMQ
一、生产者
1、配置文件application.yml
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /
2、配置类
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "m_exchange";
public static final String QUEUE_NAME = "m_queue";
/**
* 交换机
* @return
*/
@Bean("mExchange")
public Exchange mExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
/**
* 队列
* @return
*/
@Bean("mQueue")
public Queue mQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
/**
* 绑定交换机和队列
* @param exchange
* @param queue
* @return
*/
@Bean
public Binding mBinding(@Qualifier("mExchange") Exchange exchange,@Qualifier("mQueue") Queue queue){
return BindingBuilder.bind(queue).to(exchange).with("myx.#").noargs();
}
}
3、调用RabbitTemplate发送消息
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerTest {
//注入RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void sendTest(){
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"myx.hello","你好!RabbitMQ");
}
}
二、消费者
1、配置文件,同上
2、RabbitListener接收消息
@Component
public class RabbitMQListener {
@RabbitListener(queues = "m_queue")
public void mQueueListener(Message message){
System.out.println(message);
System.out.println(new String(message.getBody()));
}
}
3、运行结果
(Body:'你好!RabbitMQ' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=m_exchange, receivedRoutingKey=myx.hello, deliveryTag=1, consumerTag=amq.ctag-_z-LCEXYGpAhw-spYrRsyg, consumerQueue=m_queue])
你好!RabbitMQ