首先引入pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

手动创建队列

  1. 接收端
在rabbitmq页面添加 myQueue 队列
@Log4j2
@Component
public class MqReceiver {

    @RabbitListener(queues = "myQueue")
    public void process(String message) {
        log.info("MqReceiver: {} ", message);
    }
}
  1. 发送端
应用需要先启动
@Log4j2
@Component
public class MqReceiverTest extends SpringDomeApplicationTests {

    @Autowired
    AmqpTemplate amqpTemplate;

    @Test
    public void process() {
        log.info("123");
        amqpTemplate.convertAndSend("myQueue", "测试mq,简单发送,简单接受!");
    }
}

自动创建队列

  1. 接收端
    /**
     * 自动创建队列
     *
     * @param message
     */
    @RabbitListener(queuesToDeclare = @Queue("autoQueue"))
    public void autoCreateMq(String message) {
        log.info("接受自动创建的队列消息: {} ", message);
    }
  1. 发送端
    @Test
    public void autoCreateMq() {
        amqpTemplate.convertAndSend("autoQueue", "测试mq自动创建队列,");
    }

自动绑定exchanges

使用场景 一个exchanges可以绑定多个队列queue; 比如一个订单里面有两种商品 A,B;需要同时发送给A,B的库存服务修改库存数量
  1. 接收端

    /**
     * 自动绑定exchange
     *
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("autoExchangeQueue"),
            exchange = @Exchange("autoExchange")
    ))
    private void autoExchange(String message) {
        log.info("自动绑定exchange: {} ", message);
    }
  1. 发送端
    @Test
    public void autoExchange() {
        amqpTemplate.convertAndSend("autoExchangeQueue", "测试mq自动创建队列和绑定exchange,");
    }

exchanges使用场景

  1. 接收端
    /**
     * 给老王发通知,绑定autoExchange
     *
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange("autoExchange"),
            key = "lw",
            value = @Queue("lwQueue")
    ))
    private void noticeMrW(String message) {
        log.info("老王, {} ", message);
    }

    /**
     * 给老张发通知,绑定autoExchange
     *
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange("autoExchange"),
            key = "lz",
            value = @Queue("lzQueue")
    ))
    private void noticeMrZ(String message) {
        log.info("老张, {} ", message);
    }
  1. 发送端
注意绑定是exchange( autoExchange)

    @Test
    public void noticeMrW() {
        amqpTemplate.convertAndSend("autoExchange", "lw", "老张来了");
    }

    @Test
    public void noticeMrZ() {
        amqpTemplate.convertAndSend("autoExchange", "lz", "老王来了");
    }
Last modification:February 13th, 2020 at 03:53 pm
如果觉得我的文章对你有用,请随意赞赏