• RabbitMQ学习笔记(2)----RabbitMQ简单队列(Hello World)的使用


    1. 简单队列结构图

      

    2. 引入依赖

      pom.xml文件

     <dependency>
          <groupId>com.rabbitmq</groupId>
          <artifactId>amqp-client</artifactId>
          <version>5.5.0</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.8.0-beta2</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-simple</artifactId>
          <version>1.8.0-beta2</version>
        </dependency>

    3. 生产者生产消息

      Producer如下:

    package com.wangx.rabbitmq.helloworld;
    
    import com.rabbitmq.client.Channel;
    import com.rabbitmq.client.Connection;
    import com.rabbitmq.client.ConnectionFactory;
    
    import java.io.IOException;
    import java.util.concurrent.TimeoutException;
    
    public class Producer {
    
        /**
         * 队列名字
         */
        private static final String QUEUE_NAME = "MyQueue";
        public static void main(String[] args) throws IOException, TimeoutException {
    
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            //设置服务器主机
            factory.setHost("localhost");
            //设置用户名
            factory.setUsername("wangx");
            //设置密码
            factory.setPassword("wangx");
            //设置VirtualHost
            factory.setVirtualHost("/wangx");
            Connection connection = null;
            Channel channel = null;
            try {
    
                //创建连接
                connection = factory.newConnection();
                //创建消息通道
                channel = connection.createChannel();
                //声明队列
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                String message = "Hello World!";
                //发送消息
                for (int i = 0; i < 10; i++) {
                    //发送消息
                    channel.basicPublish("", QUEUE_NAME, null, (message + i).getBytes());
                    System.out.println(" [x] Sent '" + message + i + "'");
                }
            }catch (Exception e) {
                e.printStackTrace();
            } finally {
                channel.close();
                connection.close();
            }
        }
    }

      运行发送消息,然后查看控制台:

      

      可以看到已经存在了刚刚的十条消息了。

    4. 消费者消费消息

    package com.wangx.rabbitmq.helloworld;
    
    import com.rabbitmq.client.*;
    import com.rabbitmq.client.impl.recovery.QueueRecoveryListener;
    
    import java.io.IOException;
    import java.util.concurrent.TimeoutException;
    
    public class MyConsumer {
        /**
         * 队列名字
         */
        private static final String QUEUE_NAME = "MyQueue";
        public static void main(String[] args) throws IOException, TimeoutException {
    
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            //设置服务器主机
            factory.setHost("localhost");
            //设置用户
            factory.setUsername("wangx");
            //设置密码
            factory.setPassword("wangx");
            //设置VirtualHost
            factory.setVirtualHost("/wangx");
            Connection connection = null;
            Channel channel = null;
            try {
    
                //创建连接
                connection = factory.newConnection();
                //创建消息通道
                channel = connection.createChannel();
                //声明队列
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                Consumer consumer = new DefaultConsumer(channel){
                    //重写DefaultConsumer中handleDelivery方法,在方法中获取消息
                    @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("收到消息 '" + message + "'");
                    }
                };
                //监听消息
                channel.basicConsume(QUEUE_NAME, true,consumer);
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
            }
        }
    }

      启动消费者,可以看到将会成功消费刚刚生产的十条消息。

      控制台打印如下:

    收到消息 'Hello World!0'
    收到消息 'Hello World!1'
    收到消息 'Hello World!2'
    收到消息 'Hello World!3'
    收到消息 'Hello World!4'
    收到消息 'Hello World!5'
    收到消息 'Hello World!6'
    收到消息 'Hello World!7'
    收到消息 'Hello World!8'
    收到消息 'Hello World!9'

      查看rabbitmq:

      

      刚刚生产者生产的消息已经不存在了,表示已经被消费了。

  • 相关阅读:
    Spring 中出现Element : property Bean definitions can have zero or more properties. Property elements correspond to JavaBean setter methods exposed by the bean classes. Spring supports primitives, refer
    java定时器schedule和scheduleAtFixedRate区别
    hql语句中的select字句和from 字句
    使用maven搭建hibernate的pom文件配置
    Failure to transfer org.apache.maven:maven-archiver:pom:2.5 from http://repo.maven.apache.org/ maven2 was cached in the local repository, resolution will not be reattempted until the update interv
    对于文件File类型中的目录分隔符
    hibernate的事务管理和session对象的详解
    解决mac 中的myeclipse控制台中文乱码问题
    ibatis selectKey用法问题
    Java中getResourceAsStream的用法
  • 原文地址:https://www.cnblogs.com/Eternally-dream/p/9968542.html
Copyright © 2020-2023  润新知