从零开始学习SpringBoot

SpringBoot - 调用RabbitMQ

2018-06-05  本文已影响181人  BzCoder

相关资料:

一.配置环境

添加MAVEN依赖。

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

配置参数。端口用户名密码都有默认参数。

spring:
  rabbitmq:
    host: 192.168.15.128

接下去按照规矩查看自动配置类RabbitAutoConfiguration,于是我们找到了用户管理类amqpAdmin 以及队列操作类rabbitTemplate

二.amqpAdmin

amqpAdmin可以用于交换器,队列以及绑定的申明,以下代码演示了amqpAdmin的主要用法。

    @Autowired
    AmqpAdmin amqpAdmin;

 @Test
    public void contextLoads() {
        //新建交换器
        amqpAdmin.declareExchange(new DirectExchange("springBoot.directExchange"));
        amqpAdmin.declareExchange(new FanoutExchange("springBoot.fanoutExchange"));
        amqpAdmin.declareExchange(new TopicExchange("springBoot.topicExchange"));
        //新建队列
        amqpAdmin.declareQueue(new Queue("springBoot.queue", true));
        //绑定
        amqpAdmin.declareBinding(new Binding("springBoot.queue", Binding.DestinationType.QUEUE, "springBoot.fanoutExchange", "", null));
        amqpAdmin.declareBinding(new Binding("springBoot.queue", Binding.DestinationType.QUEUE, "springBoot.topicExchange", "springBoot.*", null));
        amqpAdmin.declareBinding(new Binding("springBoot.queue", Binding.DestinationType.QUEUE, "springBoot.directExchange", "", null));
    }

    @Test
    public void remove() {
        //移除交换器
        amqpAdmin.deleteExchange("springBoot.directExchange");
        amqpAdmin.deleteExchange("springBoot.fanoutExchange");
        amqpAdmin.deleteExchange("springBoot.topicExchange");
        //移除队列
        amqpAdmin.deleteQueue("springBoot.queue");
    }

三 .rabbitTemplate

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Test
    public void send() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "baozhou");
        map.put("age", 18);
        map.put("data", Arrays.asList("666", "你好", 123));
        rabbitTemplate.convertAndSend("springBoot.directExchange", "springBoot.queue", map);
        rabbitTemplate.convertAndSend("springBoot.fanoutExchange", "", new testBean("baozhou", "27"));
    }

   @Test
    public void receive() {
        Object bean = rabbitTemplate.receiveAndConvert("springBoot.queue");
        System.out.println("结果:" + bean);
    }

当然和Redis一样,SpringBoot默认使用的是JAVA默认序列器,会把对象序列化存储,我们可以重启定义消息序列器。

/**
 * @author BaoZhou
 * @date 2018/6/5
 */

@Configuration
@EnableRabbit
public class RabbitMQConfig {

    @Bean
    public MessageConverter MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

}

替换序列化器后我们得到的就是Json对象了


Json对象

四.消息监听

要实现消息监听,主要就是两个注解@EnableRabbit,以及@RabbitListener(queues = queueName)

@Service
public class amqpService {
    @RabbitListener(queues = "springBoot.queue")
    public void recevie(testBean bean) {
        System.out.println("监听到消息了");
        System.out.println(bean);
    }
}
消息监听

有关于RabbitMQ的简单介绍就到这里,真的很简单。

上一篇 下一篇

猜你喜欢

热点阅读