在下图中,“P”是我们的生产者,“C”是我们的消费者。中间的框是队列 - RabbitMQ代表消费者的消息缓冲区。

本例使用maven构建项目,在pom.xml中添加一下依赖

<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.1.</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.</version>
</dependency> </dependencies>

接下来通过生产者叫rabbitMQ服务器发送一个消息,这个消息被缓存在了rabbitMQ的队列中,生产者相当于发件人,rabbitMQ相当于申通快递,消费者相当于接收人

定义一个发件人Send.java

 package com.rabbitMQ;

 import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory; /**
* 发送消息后,如果服务器的队列中没有可发现的消费者,那么就会放在队列中等待消费者
* 可以使用rabbitmqctl.bat list_queues命令查看某个队列的消息个数
* @author may
*
*/
public class Send { private final static String QUEUE_NAME = "hello"; public static void main(String[] args) throws Exception {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置连接rabbitMQ服务器的ip
factory.setHost("localhost");
// factory.setPort(5672);
//创建一个连接到服务器的链接
Connection connection = factory.newConnection();
//创建连接通道
Channel channel = connection.createChannel(); /**
* 定义一个队列
* queueDeclare(String queue,//队列的名字
* boolean durable, //定义一个耐用队列,即持久化,如果RabbitMQ服务挂机,重启后还能恢复这个队列。
* boolean exclusive, //排他队列,只能在当前链接中可用,如果这个连接关闭,那么也就无效了。
* boolean autoDelete,//在连接断开后自动删除队列。
* Map<String, Object> arguments)
*/
channel.queueDeclare(QUEUE_NAME, false, false, false, null); // channel.queueDeclareNoWait(queue, durable, exclusive, autoDelete, arguments); String message = "Hello World!";
/**
* Parameters:
* exchange: the exchange to publish the message to 转发器的名字
* routingKey: the routing key 路由key,这里就是队列的名字,表示要发送到这个队列上
* props: other properties for the message - routing headers etc//这个信息的属性
* body: the message body 要发送的信息
*/
channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close();
} }

接收消息,消费者从队列中获取消息

 
定义一个Recv.java
 
package com.rabbitMQ;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope; public class Recv {
//队列名要和发送者定义的队列一样的名字,它会告诉rabbitMQ它要再哪个队列中获取消息
private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
/**
* 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);
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.println(" [x] Received '" + message + "'");
}
};
//异步
/**
* queue the name of the queue 队列名
* 如果autoAck设置为true,这个Consumer在收到消息之后会马上返回ack。服务器将立即删除在内存中排队的消息
* false 在消息的任务处理完之后再手动ack,如果正在处理的时候,消费者发生异常,就不能返回ack,那么就不会删除这个消息,等待发现其他消费者发送给他们
autoAck true if the server should consider messages acknowledged once delivered; false if the server should expect explicit acknowledgements
callback an interface to the consumer object
*/
channel.basicConsume(QUEUE_NAME, true, consumer); //rabbitmqctl.bat list_queues 命令可以列出当前有多少个队列
}
}

运行Send,向rabbitMQ发送了一个消息,我们可以通过rabbitMQ的一个工具查看当前的队列中有多少个消息在排队。

hello是队列的名字,1表示当前的队列中存在一个消息等待着被消费者处理

这个时候,启动消费者去取快递,启动后输出一下内容,成功打印出了Hello World

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

再次查看rabbitMQ中hello队列中的消息个数

消息个数为零。

rabbitMQ_helloworld(一)的更多相关文章

随机推荐

  1. 利用GitLab自动同步软件仓库

    利用GitLab自动同步GitHub.Gitee.Bitbucket软件仓库 我在码云的账号:userName密码:password项目地址:https://gitee.com/Bytom/bytom ...

  2. SpringBoot实现文件上传

    前言参考:快速开发第一个SpringBoot应用 这篇文章会讲解如何使用SpringBoot完成一个文件上传的过程,并且附带一些SpringBoot开发中需要注意的地方 首先我们写一个文件上传的htm ...

  3. HBase 学习之路(四)—— HBase集群环境配置

    一.集群规划 这里搭建一个3节点的HBase集群,其中三台主机上均为Regin Server.同时为了保证高可用,除了在hadoop001上部署主Master服务外,还在hadoop002上部署备用的 ...

  4. 初步接触 Java Net 网络编程

    本文目的是大概了解 Java 网络编程体系,需要一点点 Java IO 基础,推荐教程 系统学习 Java IO.主要参考 JavaDoc 和 Jakob Jenkov 的英文教程<Java N ...

  5. 【dateFormatSymbols】JAVA特殊日期格式转换

    记录:特殊日期格式转换,如将yyyyMMdd转为01MAY2019 public static final String DATE_VIP_FORMAT = "yyyyMMdd"; ...

  6. docker容器中使用pip有警告

    docker容器中使用pip有警告 /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:334: ...

  7. mysql 正确清理binlog日志的两种方法

    前言: MySQL中的binlog日志记录了数据库中数据的变动,便于对数据的基于时间点和基于位置的恢复,但是binlog也会日渐增大,占用很大的磁盘空间,因此,要对binlog使用正确安全的方法清理掉 ...

  8. 思维导图xmind的使用方法

    什么是Xmind Xmind是一款简单好用的思维导图软件,除了可以轻松绘制基本逻辑图,还支持组织结构图(竖直).树状图(水平+竖直).思维导图(辐射).鱼骨图.二维图(表格)模型.免费版可以把思维导图 ...

  9. Win32小游戏--蜘蛛纸牌

    前一段时间完成了蜘蛛纸牌的仿写,现将过程和思路记录下来 首先,为了符合复用性,在win32的基本框架中,把可变的部分用c++封装起来成为一系列虚函数,这样如果再继续写游戏的话,只需要继承这个类就可以了 ...

  10. 风险:隐蔽权限修改导致rgw服务中断

    上午正在开会,突然收到rgw服务异常的告警(503 Service Unavailable),立马停下来处理告警,避免影响到用户~   我们的rgw frontend用的是apache,之前也遇到过5 ...