RabbitMQ - 简单使用

一、理解

  1.步骤

  •  建立虚拟主机virtual hosts
  •  建立交换器Exchanges(交换器主要是三种类型direct,fanout, topic)
  •  建立队列Queues
  •  队列与交换器绑定,在此过程中指定绑定的路由键 --> 路由键可以精确匹配也可以使用 # 进行模糊匹配(匹配零个或多个)

二、简单使用测试

  /**
     * mq控制类
     */
    @Autowired
    private AmqpAdmin amqpAdmin;
    /**
     * mq调用类
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;


    //创建交换器
    @Test
    public void contextLoads() {
        amqpAdmin.declareExchange(new DirectExchange("myone"));//持久化:DirectExchange(String name, boolean durable, boolean autoDelete)- autoDelete 是否持久化
        amqpAdmin.declareExchange(new FanoutExchange("mytwo"));
    }

    //创建队列
    @Test
    public void cont213213extLoads() {
        amqpAdmin.declareQueue(new Queue("haone"));//持久化:Queue(String name, boolean durable) - autoDelete 是否持久化
        amqpAdmin.declareQueue(new Queue("hatwo"));
    }

    //绑定并指定路由键
    @Test
    public void cont2132sadasd13extLoads() {
        amqpAdmin.declareBinding(new Binding("haone", Binding.DestinationType.QUEUE,"myone","keyone",null));
        amqpAdmin.declareBinding(new Binding("hatwo", Binding.DestinationType.QUEUE,"mytwo","keytwo",null));
        amqpAdmin.declareBinding(new Binding("haone", Binding.DestinationType.QUEUE,"mytwo","keythree",null));
    }

    //发送点对点消息
    @Test
    public void cont2132sasfgdsgdasd13extLoads() {
        Map<String,String> map = new HashMap<String,String>();
        map.put("方哈儿","大笨蛋");
        rabbitTemplate.convertAndSend("myone","keyone",map);
    }
    //发送订阅消息
    @Test
    public void cont2132sadasdfghfghgfg13extLoads() {
     //要判断是否为null,因为消费后,消息就消失了, Object haone
= rabbitTemplate.receiveAndConvert("haone"); System.out.println(haone.getClass()); System.out.println(haone); }

 三、是否序列话成json,需要的话要添加一个配置类

@Configuration
public class CustomerRabbitMQConfig {

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

 四、配置文件

spring:
  rabbitmq:
    host: localhost
    virtual-host: rlzy
    username: lalademaxiya
    password: 123456

 

posted @ 2019-06-11 21:38  iapetosee  阅读(280)  评论(0编辑  收藏  举报