Springboot利用AmqpTemplate整合Rabbitmq

上一篇 << 下一篇 >>>Rabbitmq如何保证幂等性


1.注意点

a、队列绑定的key必须和@bean时的方法名一致才可以自动识别
b、队列和交换机会自动生成

2.核心代码

2.1 依赖包引入



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

2.2 配置信息

spring:
  rabbitmq:
    ####连接地址
    host: 10.211.55.16
    ####端口号
    port: 5672
    ####账号
    username: jarye
    ####密码
    password: 123456
    ### 地址
    virtual-host: /mytest1205

2.3 bean初始化

@Component
public class RabbitMQConfig {
    /**
     * 定义交换机
     */
    private String EXCHANGE_SPRINGBOOT_NAME = "springboot_topic_exchange";

    /**
     * 短信队列
     */
    private String FANOUT_SMS_QUEUE = "springboot_topic_sms_queue";
    /**
     * 邮件队列
     */
    private String FANOUT_SMS_EMAIL = "springboot_topic_email_queue";

    /**
     * 创建短信队列
     */
    @Bean
    public Queue smsQueue() {
        return new Queue(FANOUT_SMS_QUEUE);
    }

    /**
     * 创建邮件队列
     */
    @Bean
    public Queue emailQueue() {
        return new Queue(FANOUT_SMS_EMAIL);
    }

    /**
     * 创建交换机
     *
     * @return
     */
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(EXCHANGE_SPRINGBOOT_NAME);
    }

    /**
     * 定义短信队列绑定交换机
     */
    @Bean
    public Binding smsBindingExchange(Queue smsQueue, TopicExchange topicExchange) {
        return BindingBuilder.bind(smsQueue).to(topicExchange).with("my.sms");
    }

    /**
     * 定义邮件队列绑定交换机
     */
    @Bean
    public Binding emailBindingExchange(Queue emailQueue, TopicExchange topicExchange) {
        return BindingBuilder.bind(emailQueue).to(topicExchange).with("my.#");
    }
}

2.4 生产者

@RestController
public class FanoutProducer {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping("/sendMsg")
    public String sendMsg(String msg) {
        // 参数1 交换机名称 、参数2路由key  参数3 消息
        amqpTemplate.convertAndSend("springboot_topic_exchange", "my.time", msg);
        return "success";
    }
}

2.5 消费者

@Component
@RabbitListener(queues = "springboot_topic_email_queue")
public class FanoutEmailConsumer {

    @RabbitHandler
    public void consumer(String msg){
        System.out.println("邮件消费者收到消息:"+msg);
    }
}
@Component
@RabbitListener(queues = "springboot_topic_sms_queue")
public class FanoutSmsConsumer {

    @RabbitHandler
    public void consumer(String msg){
        System.out.println("短信消费者收到消息:"+msg);
    }
}

推荐阅读:
<<<消息中间件的核心思想
<<<消息中间件常见问题汇总
<<<基于Netty简单手写消息中间件思路
<<<消息队列常用名词与中间件对比
<< << << << << << << << << << << << << << << << << << << << << << << << << << << << << << << <<

你可能感兴趣的:(Springboot利用AmqpTemplate整合Rabbitmq)