image-20181205151420002

image-20181205151512556

1.加入依赖

1
2
3
4
5
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<scope>3.6.5</scope>
</dependency>

2.编码实战

2.1Productor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public class Procuder {
// 生产端Procuder http://94.191.24.33:15672/#/
public static void main(String[] args) throws Exception {
// 1.创建一个ConnectionFactory 并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("94.191.24.33");
connectionFactory.setPort(15672);
connectionFactory.setVirtualHost("/");
// 2.通过连接工厂创建连接connectionFactory.newConnection();
Connection connection = connectionFactory.newConnection();

// 3.通过connection创建一个Channel
Channel channel = connection.createChannel();
// 4.通过Channel发送数据

String msg = "Hello RabbitMQ";
//channel.basicPublish(exchange, routingKey, props, body);
channel.basicPublish("", "test001", null, msg.getBytes());
channel.close();
connection.close();
}

image-20181205160320034


2.2.Consumer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Consumer {

public static void main(String[] args) throws Exception {
// 1.创建一个ConnectionFactory,并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("94.191.24.33");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");

// 2.通过连接工厂创建连接
Connection connection = connectionFactory.newConnection();

// 3 通过连接工厂创建连接
Channel channel = connection.createChannel();

// 4.申明(创建)一个队列
String queueName = "test001";
// channel.queueDeclare(queueName, durable, exclusive, autoDelete, arguments)
channel.queueDeclare("test001", true, false, false, null);

// 5.创建消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

/**
* 6.设置channel # channel.basicConsume(queue,autoAck, autoAck) # 1:queue:队列的名字
* 2.autoAck:是否自动签收 3:autoAck:具体的消费者对象
*/
channel.basicConsume(queueName, true, queueingConsumer);

//7.获取消息
while (true) {
Delivery delivery = queueingConsumer.nextDelivery();
String msg = new String(delivery.getBody());// 获取消息
System.out.println("消费端" + msg);
}
}
}

image-20181205165853880


2.3 启动程序看管控台

image-20181205170034688

image-20181205170103019

image-20181205170136237

image-20181205170239009

2.4 方法的API

3.一些基础

image-20181205170337122

image-20181205170521505

image-20181205170707823

image-20181205170738566