您的位置:首页 > 其它

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

2018-02-09 17:39 615 查看

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
已经完成
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: