SpringBoot集成RabbitMQ

SpringBoot集成RabbitMQ

  • 第一步:先下载erlang和rabbitMQ-server(安装教程省略)
  • 第二步:SpringBoot的pom中添加依赖
  • <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    

    第三步:在application.properties中进行配置;

  • #rabbitmq
    spring.rabbitmq.host=127.0.0.1
    spring.rabbitmq.port=5672
    spring.rabbitmq.username=guest
    spring.rabbitmq.password=guest
    spring.rabbitmq.virtual-host=/
    #表示消费者数量,如果为1相当于是串行
    spring.rabbitmq.listener.simple.concurrency=10
    spring.rabbitmq.listener.simple.max-concurrency=10
    #表示每次从队列中取,取多少个
    spring.rabbitmq.listener.simple.prefetch=1
    #消费者自动启动
    spring.rabbitmq.listener.simple.auto-startup=true
    #消费者消费失败后把数据重新加入到队列中去
    spring.rabbitmq.listener.simple.default-requeue-rejected=true
    #下面是重试的配置,分别表示:
    #允许重试,初始1秒重试一次,最多重试3次,最大间隔是10秒
    spring.rabbitmq.template.retry.enabled=true 
    spring.rabbitmq.template.retry.initial-interval=1000
    spring.rabbitmq.template.retry.max-attempts=3
    spring.rabbitmq.template.retry.max-interval=10000
    #multiplier表示如果前一次重试间隔为i秒,下一次为i * multiplier秒
    spring.rabbitmq.template.retry.multiplier=1.0
    

     

  • 第四步:写rabitmq的config文件;
  • 交换机Exchange一共有四种模式,分别为:Direct模式,Topic模式,Fanout模式,Header模式。这里统一给出配置,之后再分别演示其作用。

  • package com.admin.demo;
    
    import org.springframework.amqp.core.*;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Configuration
    public class MQConfig {
    
        public static final String MIAOSHA_QUEUE = "miaosha.queue";
        public static final String QUEUE = "queue";
        public static final String TOPIC_QUEUE1 = "topic.queue1";
        public static final String TOPIC_QUEUE2 = "topic.queue2";
        public static final String HEADER_QUEUE = "header.queue";
        public static final String TOPIC_EXCHANGE = "topicExchage";
        public static final String FANOUT_EXCHANGE = "fanoutxchage";
        public static final String HEADERS_EXCHANGE = "headersExchage";
    
        /**
         * Direct模式 交换机Exchange
         */
        @Bean
        public Queue queue() {
            return new Queue(QUEUE, true);
        }//队列参数的意义是:名称+是否要初始化
    
        /**
         * Topic模式 交换机Exchange
         */
        @Bean
        public Queue topicQueue1() {
            return new Queue(TOPIC_QUEUE1, true);
        }
    
        @Bean
        public Queue topicQueue2() {
            return new Queue(TOPIC_QUEUE2, true);
        }
    
        @Bean
        public TopicExchange topicExchage() {
            return new TopicExchange(TOPIC_EXCHANGE);
        }
    
        @Bean
        public Binding topicBinding1() {
            return BindingBuilder.bind(topicQueue1()).to(topicExchage()).with("topic.key1");
        }
    
        @Bean
        public Binding topicBinding2() {
            return BindingBuilder.bind(topicQueue2()).to(topicExchage()).with("topic.#");
        }
    
        /**
         * Fanout模式 交换机Exchange
         */
        @Bean
        public FanoutExchange fanoutExchage() {
            return new FanoutExchange(FANOUT_EXCHANGE);
        }
    
        @Bean
        public Binding FanoutBinding1() {
            return BindingBuilder.bind(topicQueue1()).to(fanoutExchage());
        }
    
        @Bean
        public Binding FanoutBinding2() {
            return BindingBuilder.bind(topicQueue2()).to(fanoutExchage());
        }
    
        /**
         * Header模式 交换机Exchange
         */
        @Bean
        public HeadersExchange headersExchage() {
            return new HeadersExchange(HEADERS_EXCHANGE);
        }
    
        @Bean
        public Queue headerQueue1() {
            return new Queue(HEADER_QUEUE, true);
        }
    
        @Bean
        public Binding headerBinding() {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("header1", "value1");
            map.put("header2", "value2");
            return BindingBuilder.bind(headerQueue1()).to(headersExchage()).whereAll(map).match();
        }
    }
    

     

  • 第五步:写生产者sender和消费者receiver;(以Direct模式为例)
  • 生产者:

  • package com.admin.demo;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.amqp.core.AmqpTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class MQSender {
    
        private static Logger log = LoggerFactory.getLogger(MQSender.class);
    
        @Autowired
        AmqpTemplate amqpTemplate; //操作queue的工具类
    
        public void send(Object message) {
            String msg = message.toString();
            log.info("send message:" + msg);
            amqpTemplate.convertAndSend(MQConfig.QUEUE, msg);
        }
    }
    

    消费者:

  • package com.admin.demo;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    public class MQReceiver {
    
        private static Logger log = LoggerFactory.getLogger(MQReceiver.class);
    
        @RabbitListener(queues = MQConfig.QUEUE)
        public void receive(String message) {
            log.info("receive message:" + message);
        }
    }
    
    

     第6步:Controller层验证实现的消息队列

  • package com.admin.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Controller
    @RequestMapping("/demo")
    public class DemoController {
    
        @Autowired
        MQSender sender;
    
        @RequestMapping("/mq")
        @ResponseBody
        public Map<String,Object> mq() {
            Map<String,Object> result =new HashMap<>();
            sender.send("hello,imooc");
            result.put("result","success");
            return result;
        }
    }
    
    

     结果展示
    在浏览器中输入http://localhost:8080/demo/mq,返回json串 

    {"result":"success"}
  • 控制台输出

  •  

     至此,rabbitmq 配置成功!!!

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值