RabbitMQ工具类

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.saxon.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Objects;

/**
* @author saxon
*/
public class RabbitMQUtils {
private static ConnectionFactory connectionFactory;

static {
connectionFactory = new ConnectionFactory ();
//设置连接的主机
connectionFactory.setHost ("120.79.3.138");
//设置端口号
connectionFactory.setPort (5672);
//设置连接的虚拟主机
connectionFactory.setVirtualHost ("ems");
//设置用户和密码
connectionFactory.setUsername ("admin");
connectionFactory.setPassword ("admin");
}

/**
* 获得连接
*
* @return 连接对象
*/
public static Connection getConnect () {
//获得连接对象
try {
return connectionFactory.newConnection ();
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}

/**
* 关闭连接
*/
public static void closeConnectAndChannel (Connection connection, Channel channel) {
try {
Objects.requireNonNull (channel).close ();
Objects.requireNonNull (connection).close ();
} catch (Exception e) {
e.printStackTrace ();
}
}
}

关闭的顺序一定要先关闭通道,再关闭连接;

消息持久化

发送端:

1
channel.queueDeclare ("hello", false, false, false, null);

接收端:

1
channel.queueDeclare ("hello", false, false, false, null);

他们的配置一样,如果我们把第二个变成true的话,那么在我们重启服务的时候,我们就可以保留队列,但是 ==他对于我们的消息不会持久化,如果我们需要消息也要持久化,那么就要在发送的时候,在props上面添加上配置==

1
channel.basicPublish ("", "hello", MessageProperties.PERSISTENT_TEXT_PLAIN, "hello world".getBytes ());

使用messageProperties的常量来配置持久化

需要注意的是,一旦我们改变消息发送方或者接收方的时候,两边的数据必须要一致,相当于我们是匹配的,如果不一样,他就不会匹配