RabbitMq 使用 | 第一篇:安装和Hello World

版权声明:本文为博主原创文章,欢迎转载,转载标明原文地址: https://blog.csdn.net/u012943767/article/details/79300649

RabbitMq 使用 | 第一篇:安装和Hello World

记录RabbitMQ官方教程的一些案例

这里使用的系统是MacOs 10.12.6,其他系统请参考Downloading and Installing RabbitMQ

  • MacOs使用HomeBrew安装
brew update
brew install rabbitmq

运行RabbitMQ服务

默认情况下Mac系统RabbitMQ安装在/usr/loca/sbin目录中,但是这个路径没有添加到环境变量中,所以需要添加环境变量以便更方便启动RabbitMQ

编辑 .bash_profile 或者 .profile 文件添加如下内容

PATH=$PATH:/usr/local/sbin

.bash_profile立即生效

source .bash_profile

此时可以选择使用 rabbitmq-server 启动服务端。

编写Hello World

在IDEA(Eclipse)创建一个Maven项目,添加如下依赖:

<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.1.2</version>
</dependency>

发送端:

public class Send {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello world";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("[x] Sent '" + message + "'");
        channel.close();
        connection.close();
    }
}

接收端:

public class Recv {

    private static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        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.print(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}

依次启动运行Send.java和Recv.java(顺序不限,前提是RabbitMQ服务已启动)

可以看到输出:

Send.java 输出如下:

[x] Sent 'Hello world'

Recv.java 输出如下:

 [*] Waiting for messages. To exit press CTRL+C
 [x] Received 'Hello world'

此时一个使用RabbitMQ发送和接收消息的Demo已经完成

猜你喜欢

转载自blog.csdn.net/u012943767/article/details/79300649