相关依赖

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

生产端

application.yml

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: heoller
    password: heoller
    virtual-host: spring-boot-study

RabbitMQConfig.java

@Configuration
public class RabbitMQConfig {

    public static final String EXCHANGE_NAME = "springboot-topic-exchange";
    public static final String QUEUE_NAME = "springboot-topic-queue";

    // 声明交换机
    @Bean
    public Exchange topicExchange() {
        // ExchangeBuilder.fanoutExchange() 广播模式
        // ExchangeBuilder.directExchange() 路由模式
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }
    // 声明队列
    @Bean
    public Queue topicQueue() {
        return QueueBuilder.durable(QUEUE_NAME).build();
    }
    // 声明绑定关系
    @Bean
    public Binding buildBinding(Exchange topicExchange, Queue topicQueue) {
        return BindingBuilder.bind(topicQueue).to(topicExchange).with("com.#").noargs();
    }
}

Producer.java测试类

@SpringBootTest
public class Producer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void doProduce() {
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "com.heoller.name", "his name is heoller");
    }
}

消费端

监听类TopicConsumer.java

@Component
public class TopicConsumer {

    @RabbitListener(queues = "springboot-topic-queue")
    public void doConsumer(Message message) {
        System.out.println("message: " + message);
    }
}