Springboot整合RabbitMq消息队列

最近公司要做一个监控信息,两个系统之间及时通信的功能,用到的是RabbitMq。为什么不用ActiveMq,搞的我还要发时间去学RabbitMq,不过模式都是差不多的,下面是我的一些理解和实现功能的代码,希望能帮到想要使用RabbitMq的同行。

简介:

RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用。消息中间件在互联网公司的使用中越来越多,刚才还看到新闻阿里将RocketMQ捐献给了apache,当然了今天的主角还是讲RabbitMQ。消息中间件最主要的作用是解耦,中间件最标准的用法是生产者生产消息传送到队列,消费者从队列中拿取消息并处理,生产者不用关心是谁来消费,消费者不用关心谁在生产消息,从而达到解耦的目的。在分布式的系统中,消息队列也会被用在很多其它的方面,比如:分布式事务的支持,RPC的调用等等。

通常我们谈到队列服务, 会有三个概念: 发消息者、队列、收消息者,RabbitMQ 在这个基本概念之上, 多做了一层抽象, 在发消息者和 队列之间, 加入了交换器 (Exchange). 这样发消息者和队列就没有直接联系, 转而变成发消息者把消息给交换器, 交换器根据调度策略再把消息再给队列。

话不多说,直接进入正题。

第一步 在pom.xml中添加RabbitMq依赖

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-amqp</artifactId>

</dependency>

第二步 在配置文件 application.properties中添加rabbitmq相关的配置 包括rabbitmq的安装地址、端口以及账户信息等

spring.rabbitmq.host=192.168.0.88//
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbitmq
spring.rabbitmq.password=rabbitmq
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.virtual-host=/

第三步 书写RabbitMqConfig类

@Configuration
public class RabbitMqConfig {

   @Value("${spring.rabbitmq.host}")
   public String host;
   @Value("${spring.rabbitmq.port}")
   public int port;
   @Value("${spring.rabbitmq.username}")
   public String username;
   @Value("${spring.rabbitmq.password}")
   public String password;
   @Value("${spring.rabbitmq.virtual-host}")
   public String virtualHost;
    @Value("${spring.application.name}")
   public  String projectName;

   /**
    * 获取连接工厂
    * @return
    */
   @Bean
   public ConnectionFactory getConnection() {
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost(host);
      factory.setPort(port);
      factory.setUsername(username);
      factory.setPassword(password);
      factory.setVirtualHost(virtualHost);
      return factory;
   }
}

第四步 定义数据交换方式枚举

public class RabbitMqEnum {
   
   /**
     * @param
     * @Description:定义数据交换方式
     * @return
     */
    public enum Exchange {

       /**
        * fanout广播交换方式
        */
       EXCHANGE_NAME("order_control", "order_control");

        private String code;
        private String name;

        Exchange(String code, String name){
            this.code = code;
            this.name = name;
        }

        public String getCode() {
            return code;
        }

        public String getName() {
            return name;
        }
    }
}

第五步 定义消息的发送者RabbitMqSender

@Component
public class RabbitMqSender {

   @Autowired
   RabbitMqConfig config;
   
   public void send(String message) throws Exception {
      ConnectionFactory factory = config.getConnection();

      Connection connection = factory.newConnection();
      Channel channel = connection.createChannel();

      channel.exchangeDeclare(RabbitMqEnum.Exchange.EXCHANGE_NAME.getName(), "fanout");

      channel.basicPublish(RabbitMqEnum.Exchange.EXCHANGE_NAME.getName(), "", null, message.getBytes("UTF-8"));
      System.out.println(" rabbit发送: " + message);

      close(channel, connection);
   }

   public void sendMsg(String exchange,String MQType,String message) throws Exception {

      ConnectionFactory factory = config.getConnection();

      Connection connection = factory.newConnection();
      Channel channel = connection.createChannel();

      channel.exchangeDeclare(exchange, MQType);

      channel.basicPublish(exchange, "", null, message.getBytes("UTF-8"));

      close(channel, connection);
   }


   public void sendMsgToOne(String exchange,String MQType,String message,String queueName) throws Exception {
      ConnectionFactory factory = config.getConnection();

      Connection connection = factory.newConnection();
      Channel channel = connection.createChannel();

      channel.exchangeDeclare(exchange, MQType);

      channel.basicPublish(exchange, queueName, null, message.getBytes("UTF-8"));

      close(channel, connection);
   }

   public void close(Channel channel,Connection connection) throws IOException, TimeoutException {
      channel.close();
      connection.close();
   }
}

第六步 定义消息的消费者

@Service
public class RabbitMqReceiver implements ApplicationListener<ContextRefreshedEvent> {

   @Autowired
   RabbitMqConfig config;

   @Value("${spring.application.name}")
   public  String projectName;

   public void onApplicationEvent(ContextRefreshedEvent event) {
      System.out.println(event.getApplicationContext().getParent().getId() + "++++++++++");
      System.out.println(projectName+"____________________");
      //
      if ( event.getApplicationContext().getParent().getId().equals("bootstrap") ) {
         ConnectionFactory factory = config.getConnection();
         Receiver(factory, RabbitMqEnum.Exchange.EXCHANGE_NAME.getCode());

         System.out.println("-----------------------------------------------------------");

      }

   }

   /**
    * 接收消息测试 test.create
    * @param factory
     */
   public void Receiver(ConnectionFactory factory,String channel_name){
      try {
         Connection connection = factory.newConnection();
         Channel channel = connection.createChannel();

         channel.exchangeDeclare(channel_name, "fanout");
         String queueName = channel.queueDeclare().getQueue();
         channel.queueBind(queueName, channel_name, "");

         Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                  byte[] body) throws IOException {
               String message = new String(body, "UTF-8");
               System.out.println("rabbit 收到一条消息 123 '" + message + "'");
            }
         };
         channel.basicConsume(queueName, true, consumer);
      } catch (Exception e) {
         // TODO: handle exception
      }
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值