pom.xml
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.1.0</version>
</dependency>
RabbitMQ 连接配置工具类
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ChannelUtils {
public static Channel getChannelInstance(String connectionDescription) {
try {
ConnectionFactory connectionFactory = getConnectionFactory();
Connection connection = connectionFactory.newConnection(connectionDescription);
return connection.createChannel();
} catch (Exception e) {
throw new RuntimeException("获取Channel连接失败");
}
}
private static ConnectionFactory getConnectionFactory() {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setAutomaticRecoveryEnabled(true);
connectionFactory.setNetworkRecoveryInterval(10000);
connectionFactory.setTopologyRecoveryEnabled(true);
return connectionFactory;
}
}
生产者发布消息
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class Producer {
private static final String pbxName = "PBX";
private static final String routingKey = "routingKey";
public static void main(String[] args) throws IOException {
Channel channel = ChannelUtils.getChannelInstance("队列消息生产者");
AMQP.BasicProperties basicProperties = producerConfig(channel, pbxName);
while (true) {
System.out.print("请输入即将发布的消息:");
Scanner str = new Scanner(System.in);
publish(channel, basicProperties, pbxName, routingKey, str.next());
System.out.println("消息已发布,请查看订阅者状态");
}
}
public static void publish(Channel channel, AMQP.BasicProperties basicProperties, String pbxName, String routingKey, String msg) throws IOException {
channel.basicPublish(pbxName, routingKey, false, basicProperties, msg.getBytes());
}
public static AMQP.BasicProperties producerConfig(Channel channel, String pbxName) throws IOException {
channel.exchangeDeclare(pbxName, BuiltinExchangeType.DIRECT, true, false, false, new HashMap<>());
AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
.deliveryMode(2)
.contentType("UTF-8")
.contentEncoding("UTF-8")
.headers(new HashMap<>())
.build();
return basicProperties;
}
}
消费者订阅消息
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Consumer {
private static final String pbxName = "PBX";
private static final String routingKey = "routingKey";
public static void main(String[] args) throws IOException {
String queueName = "queueName";
Channel channel = ChannelUtils.getChannelInstance("队列消息消费者");
AMQP.Queue.DeclareOk declareOk = consumerConfig(channel, pbxName, routingKey, queueName);
subscribe(channel, declareOk, "消费者名称");
}
public static void subscribe(Channel channel, AMQP.Queue.DeclareOk declareOk, String consumerTag) throws IOException {
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
System.out.println("consumerTag:" + consumerTag);
System.out.println("envelope:" + envelope.toString());
System.out.println("properties:" + properties.toString());
System.out.println("消息内容:" + new String(body));
}
};
channel.basicConsume(declareOk.getQueue(), true, consumerTag, defaultConsumer);
}
public static AMQP.Queue.DeclareOk consumerConfig(Channel channel, String pbxName, String routingKey, String queueName) throws IOException {
Map<String, Object> arguments = new HashMap<String, Object>();
AMQP.Queue.DeclareOk declareOk = channel.queueDeclare(queueName, true, false, false, arguments);
channel.queueBind(declareOk.getQueue(), pbxName, routingKey);
return declareOk;
}
}
部分参数说明
basicProperties:
属性 | 解释 |
---|
String contentType | 上下文类型 |
String contentEncoding | 编码集 |
Map<String,Object> headers | 消息头 |
Integer deliveryMode | 消息的投递模式 |
Integer priority | 优先级 |
String correlationId | 自定义关联ID |
String replyTo | 回复对象 |
String expiration | 过期时间 |
String messageId | 消息编号 |
Date timestamp | 发送消息时的时间戳 |
String type | 消息类型 |
arguments:
key | 解释 |
---|
x-message-ttl | 队列中的所有消息的过期时间 |
x-expires | 超过设定时间没有消费者来访问队列,就删除队列的时间(毫秒) |
x-max-length | 队列的最新的消息数量,如果超过设定数量,前面的消息将从队列中移除掉 |
x-max-length-bytes | 队列的内容的最大空间,超过该阈值就删除之前的消息 |
x-dead-letter-exchange | 如果队列中的消息被拒绝或过期,则可以根据设置的交换机对消息进行转发,重新发布 |
x-dead-letter-routing-key | 将删除的消息推送到指定的交换机对应的路由键(路由密匙) |
x-max-priority | 队列支持的最大优先级数;如果未设置,队列将不支持消息优先级,优先级大的优先被消费 |
x-queue-mode | 将队列设置为延迟模式,队列中的消息保存在磁盘中,但不会主动持久化,RabbitMQ重启后消息还是会丢失 |
x-queue-master-locator | 将队列设置为主位置模式,确定在节点集群上声明时队列主机所在的规则 |