SpringBoot 整合RabbitMq 基本使用

1、引用起步依赖,配置RabbitMq

 
	   org.springframework.boot
	   spring-boot-starter-amqp


spring:
  rabbitmq:
    host: 192.168.121.131
    port: 5672
    username: guest
    password: guest

2、服务器端发送方式

 @Test
    public void sendMessage(){
        amqpTemplate.convertAndSend("message", "测试发送消息");
    }

    @Test
    public void sendMessageByKey(){
        amqpTemplate.convertAndSend("myExchange", "fruit", "now"+ new Date());
    }

3、客户端接收方式

/**
     * 需手动创建队列 不然启动报错
     * @param message
     */
    @RabbitListener(queues = "myQueue")
    public void process(String message){
        System.out.println("process" + message);
    }

    /**
     * 自动创建队列
     * @param message
     */
    @RabbitListener(queuesToDeclare = @Queue("myQueue"))
    public void processByDeclare(String message){
        System.out.println("processByDeclare" + message);
    }

    /**
     * 绑定Exchange
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("myQueue"),
            exchange = @Exchange("myExchange")
    ))
    public void processBindExchange(String message){
        System.out.println("processBindExchange" + message);
    }

    /**
     * 根据key接收消息
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("myQueue"),
            key = "apple",
            exchange = @Exchange("myExchange")
    ))
    public void processApple(String message){
        System.out.println("apple" + message);
    }

    /**
     * 根据key接收消息
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("myQueue"),
            key = "fruit",
            exchange = @Exchange("myExchange")
    ))
    public void processFruit(String message){
        System.out.println("fruit" + message);
    }

你可能感兴趣的:(SpringBoot)