一、pom.xml依赖引入

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

二、application.yml文件中的常用配置

spring:
  rabbitmq:
    host: 192.168.159.166
    port: 5672
    username: guest
    password: guest
    virtual-host: /

三、rabbitmq配置文件

在配置文件中声明交换机、消息队列、并绑定路由。

@Configuration
public class RabbitConfiguration {

    //声明消息队列
    @Bean
    public Queue queueorderdlx(){
        return new Queue("queueorderdlx");
    }

    //声明交换机
    @Bean
    public TopicExchange exchangeorderdlx(){
        return new TopicExchange("exchangeorderdlx");
    }

    //绑定路由
    @Bean
    public Binding bindingqueueorderdlxtoexchangeorderdlx(Queue queueorderdlx, TopicExchange exchangeorderdlx){
        return BindingBuilder.bind(queueorderdlx).to(exchangeorderdlx).with("#.orderdlx.#");
    }
}

四、创建生产者

@RestController
public class MyController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RequestMapping("/email")
    public String sendEmail(){
        //String exchange, String routingKey, Object message
        rabbitTemplate.convertAndSend("", "queuehelloworld", "msg-email");
        return "email---ok";
    }
}

五、创建消费者

@Component
public class MyConsumer {

    //这个注解就是让这个方法监听指定的队列,接收消息,处理消息
    //String str,   消息体,可以写Object
    // Message message, 完整的消息对象,保护其他信息
    // Channel channel,信道对象
    @RabbitListener(queues="queuehelloworld")
    public void receiveQueuehelloworld(String str, Message message, Channel channel){
        System.out.println("接收queuehelloworld队列消息,处理消息");
        System.out.println("str="+str);
        System.out.println("message="+message);
        System.out.println("channel="+channel);
    }
}