SpringBoot整合RabbitMQ

SpringBoot整合RabbitMQ

/**
 * 自动配置
 *  1、RabbitAutoConfiguration
 *  2、有自动配置了连接工厂ConnectionFactory;
 *  3、RabbitProperties 封装了 RabbitMQ的配置
 *  4、 RabbitTemplate :给RabbitMQ发送和接受消息;
 *  5、 AmqpAdmin : RabbitMQ系统管理功能组件;
 *  	AmqpAdmin:创建和删除 Queue,Exchange,Binding
 *  6、@EnableRabbit +  @RabbitListener 监听消息队列的内容
 *
 */
@EnableRabbit  //开启基于注解的RabbitMQ模式
@SpringBootApplication
public class Springboot02AmqpApplication {

	public static void main(String[] args) {
		SpringApplication.run(Springboot02AmqpApplication.class, args);
	}
}

1、RabbitAutoConfiguration
2、有自动配置了连接工厂ConnectionFactory;
在这里插入图片描述
3、RabbitProperties 封装了 RabbitMQ的配置
在这里插入图片描述

4、 RabbitTemplate :给RabbitMQ发送和接受消息;

	@Autowired
	RabbitTemplate rabbitTemplate;
 //发送数据
    @Test
    public void contextLoads() {

        //rabbitTemplate.send(exchange,routeKey,message);

        Map<String,Object> map = new HashMap<>();
        map.put("msg","hello curry");
        map.put("data", Arrays.asList("helloworld",123,true));
        //默认使用application/x-java-serialized-object序列化规则
        rabbitTemplate.convertAndSend("exchange.direct","atwyy.news",map);

    }
    //接收数据,如何将数据转为json发送
    @Test
    public void receive(){
        Object receiveAndConvert = rabbitTemplate.receiveAndConvert("atwyy.news");
        System.out.println(receiveAndConvert.getClass());
        System.out.println(receiveAndConvert);
    }
    @Test
    public void sendMsg(){
        rabbitTemplate.convertAndSend("exchange.fanout","",new Book("围城","钱钟书"));
    }

5、 AmqpAdmin : RabbitMQ系统管理功能组件;
AmqpAdmin:创建和删除 Queue,Exchange,Binding

   @Autowired
    AmqpAdmin amqpAdmin;

//    //创建转换器
//    @Test
//    public  void createExchange(){
//        amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
//        System.out.println("创建amqpadmin.exchange");
//    }
//    //创建队列
//    @Test
//    public void createQueue(){
//        amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
//        System.out.println("创建amqpadmin.queue");
//    }
//    //绑定
//    @Test
//    public void createBinding(){
//        amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.hh",null));
//    }

6、@EnableRabbit + @RabbitListener 监听消息队列的内

@Service
public class BookService {
    @RabbitListener(queues = "atwyy.news")
    public void receive(Book book){
        System.out.println("收到消息: " + book);
    }
    @RabbitListener(queues = "atwyy")
    public void receive02(Message message){
        System.out.println(message.getBody());
        System.out.println(message.getMessageProperties());
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值