Rabbitmq 入门

Rabbitmq 入门

测试案例

上代码 生产者消费者模型

导入jar

     <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>4.2.1</version>
      </dependency>

提供者

public class Producer {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception{
        ConnectionFactory cf = new ConnectionFactory();
        //rabbitmq监听IP
        cf.setHost("127.0.0.1");
        //rabbitmq默认监听端口,注意要记得开启端口
        cf.setPort(5672);
        //设置访问的用户
        cf.setUsername("immortal");
        cf.setPassword("immortal");
        cf.setVirtualHost("/");
        //建立连接
        Connection conn = cf.newConnection("生产者");
        //创建消息通道
        Channel channel = conn.createChannel();

        String msg = "hello rabbitmq";
        //创建hello队列
//        参数:
//        queue – the name of the queue
//        durable – true if we are declaring a durable queue (the queue will survive a server restart)
//        exclusive – true if we are declaring an exclusive queue (restricted to this connection)
//        autoDelete – true if we are declaring an autodelete queue (server will delete it when no longer in use)
//        arguments – other properties (construction arguments) for the queue
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //发送消息
        channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());

        System.out.println("send msg "+ msg + " to ["+ QUEUE_NAME +"] queue !");

        channel.close();
        conn.close();

    }
}

消费者

public class Consumer {
    private final static String QUEUE_NAME = "hello";
    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory cf = new ConnectionFactory();
        //rabbitmq监听IP
        cf.setHost("127.0.0.1");
        //rabbitmq默认监听端口,注意要记得开启端口
        cf.setPort(5672);

        //设置访问的用户
        cf.setUsername("immortal");
        cf.setPassword("immortal");
        cf.setVirtualHost("/");
        //建立连接
        Connection conn = cf.newConnection();
        //创建消息通道
        Channel channel = conn.createChannel();

        //创建hello队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" Waiting for msg....");
        //创建消费者,并接受消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("接受消息 = '" + msg + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
posted @ 2021-06-30 15:18  immortal_mode  阅读(48)  评论(0)    收藏  举报