RabbitMQ java client Hello world程序

来源:互联网 发布:基础网络知识 编辑:程序博客网 时间:2024/05/16 14:29

RabbitMQ java client Hello world程序

本文主要参考:
http://www.rabbitmq.com/tutorials/tutorial-one-java.html

好,下面上货。

先介绍一下这个程序,这个消费和生产程序是采用直接指定Queue的方式进行的。

首先引入jar包依赖:
 <dependency>      <groupId>com.rabbitmq</groupId>      <artifactId>amqp-client</artifactId>      <version>4.2.0</version>    </dependency>

然后,编写生产者程序:
package com.xueyou.rabbitdemo;import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;/** * Hello world! */public class App {    private final static String QUEUE_NAME = "hello";    public static void main(String[] args) throws Exception {        System.out.println("Hello World!");        ConnectionFactory factory = new ConnectionFactory();        factory.setHost("192.168.33.117");        factory.setPort(5672);        factory.setUsername("admin");        factory.setPassword("admin");        Connection connection = factory.newConnection();        Channel channel = connection.createChannel();        channel.queueDeclare(QUEUE_NAME, false, false, false, null);        int i = 10000;        while (i-- > 0) {            String message = "hey this is the first rabbitmq message" + i;            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());            System.out.println("sent message:" + message);            Thread.sleep(100);        }        channel.close();        connection.close();    }}

然后是消费者程序:
package com.xueyou.rabbitdemo;import com.rabbitmq.client.*;import java.io.IOException;/** * Hello world! */public class AppConsumer {    private final static String QUEUE_NAME = "hello";    public static void main(String[] args) throws Exception {        System.out.println("Hello World!");        ConnectionFactory factory = new ConnectionFactory();        factory.setHost("192.168.33.117");        factory.setPort(5672);        factory.setUsername("admin");        factory.setPassword("admin");        Connection connection = factory.newConnection();        Channel channel = connection.createChannel();        channel.queueDeclare(QUEUE_NAME, false, false, false, null);        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("receive message :" + message);            }        };        channel.basicConsume(QUEUE_NAME, true, consumer);    }}

下面是这个程序的一个解释,需要注意的是,这个程序在生产者和消费者在使用的时候都没有指定exchagne。这里不是说没有exchagne,而是使用了rabbitmq中默认的exchange。



原创粉丝点击