一、消息队列监听
实际开发中,需要监听场景
SpringBoot为了简化开发,引入了相关注解。
/** * RabbiitMQ自动配置: * 1、自动配置类:RabbitAutoConfiguration * 2、自动配置了连接工厂ConnectionFactory * 3、RabbitProperties 封装了 RabbitMQ的配置 * 4、RabbitTemplate:给RabbitMQ发送和接收消息 * 5、AmqpAdmin:RabbitMQ系统管理功能组件 * AmqpAdmin:创建和删除 Queue,Exchange,Binding * 6、@EnableRabbit + @RabbitListener(queues = {"atguigu.news"}):监听消息队列的内容 * */
1、BookService
监听消息队列
@Service
public class BookService {
/**
* 只要这个消息队列中有Book数据进入,该方法就会被调用
* @param book
*/
@RabbitListener(queues = {"atguigu.news"})
public void receive(Book book){
System.out.println("收到消息 -- " + book);
}
@RabbitListener(queues = {"atguigu"})
public void receive2(Message message){
System.out.println(message.getMessageProperties());
System.out.println(message.getBody());
}
}
2、开启基于注解的RabbitMQ模式
@EnableRabbit //开启基于注解的RabbitMQ模式
@SpringBootApplication
public class SpringbootAmqpApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAmqpApplication.class, args);
}
}
3、
二、AmqpAdmin:RabbitMQ系统管理功能组件
1、AmqpAdmin:创建和删除 Queue,Exchange,Binding
2、测试创建交换器
@SpringBootTest
class SpringbootAmqpApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private AmqpAdmin amqpAdmin;
@Test
public void createExchange(){
Exchange exchange = new DirectExchange("amqpadmin.exchange");
amqpAdmin.declareExchange(exchange);
System.out.println("创建完成...");
}
3、创建绑定规则
@Test
public void createExchange(){
/*Exchange exchange = new DirectExchange("amqpadmin.exchange");
amqpAdmin.declareExchange(exchange);
System.out.println("创建完成...");*/
/* amqpAdmin.declareQueue(new Queue("amqpadmin.queue", true));*/
//创建绑定规则
amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE , "amqpadmin.exchange", "amqp.hei", null));
}