通过Channel创建队列、交换机,发送消息以及消费消息
package com.yzm.rabbitmq_09.config;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.stereotype.Component;
@Component
public class RabbitConfig {
public static final String QUEUE = "queue_a";
public static final String FANOUT_EXCHANGE = "fanout.exchange";
public static final String FANOUT_QUEUE_A = "fanout_queue_a";
public static final String FANOUT_QUEUE_B = "fanout_queue_b";
public static final String DIRECT_EXCHANGE = "direct.exchange";
public static final String DIRECT_QUEUE_A = "direct_queue_a";
public static final String DIRECT_QUEUE_B = "direct_queue_b";
public static final String TOPIC_EXCHANGE = "topic.exchange";
public static final String TOPIC_QUEUE_A = "topic_queue_a";
public static final String TOPIC_QUEUE_B = "topic_queue_b";
public static final String TOPIC_QUEUE_C = "topic_queue_c";
public static final String HEADER_EXCHANGE = "header.exchange";
public static final String HEADER_QUEUE_A = "header_queue_a";
public static final String HEADER_QUEUE_B = "header_queue_b";
// 获取RabbitMQ服务器连接
public static Connection getConnection() {
Connection connection = null;
try {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
connection = factory.newConnection();
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
package com.yzm.rabbitmq_09.sender;
import com.rabbitmq.client.*;
import com.yzm.rabbitmq_09.config.RabbitConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
@RestController
@RequestMapping("/sender")
public class Sender {
@GetMapping("/simple")
public void simple() throws IOException, TimeoutException {
//1、获取连接
Connection connection = RabbitConfig.getConnection();
//2、创建通道,使用通道才能完成消息相关的操作
Channel channel = connection.createChannel();
/*
* 3、声明队列
* String queue 队列名称
* boolean durable 是否持久化,如果持久化,mq重启后队列还在
* boolean exclusive 是否独占连接,队列只允许在该连接中访问,如果connection连接关闭队列则自动删除,如果将此参数设置true可用于临时队列的创建
* boolean autoDelete 自动删除,队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了就自动删除)
* Map<String, Object> arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(RabbitConfig.QUEUE, true, false, false, null);
/*
* 4、发送消息
* exchange,交换机,如果不指定将使用mq的默认交换机(设置为"")
* routingKey,路由key,交换机根据路由key来将消息转发到指定的队列,如果使用默认交换机,routingKey设置为队列的名称
* props,向消费者传递的 消息属性(比如文本持久化)
* body,消息内容
*/
for (int i = 1; i <= 10; i++) {
String message = "Hello World!...... " + i;
System.out.println(" [ Sent ] 消息内容 " + message);
channel.basicPublish("", RabbitConfig.QUEUE, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
}
// 5、释放资源
channel.close();
connection.close();
}
@GetMapping("/fanout")
public void fanout() throws IOException, TimeoutException {
Connection connection = RabbitConfig.getConnection();
Channel channel = connection.createChannel();
/*
* 声明 fanout 交换机
* exchange 交换机名称
* type 交换机类型
* durable 是否可持久化
* autoDelete 是否自动删除
* internal 是否设置为内置交换机
*/
channel.exchangeDeclare(RabbitConfig.FANOUT_EXCHANGE, BuiltinExchangeType.FANOUT, true, false, false, null);
// 声明队列
channel.queueDeclare(RabbitConfig.FANOUT_QUEUE_A, true, false, false, null);
channel.queueDeclare(RabbitConfig.FANOUT_QUEUE_B, true, false, false, null);
// 队列绑定交换机,不需要路由键,用空字符串表示
channel.queueBind(RabbitConfig.FANOUT_QUEUE_A, RabbitConfig.FANOUT_EXCHANGE, "");
channel.queueBind(RabbitConfig.FANOUT_QUEUE_B, RabbitConfig.FANOUT_EXCHANGE, "");
for (int i = 1; i <= 10; i++) {
String message = "Hello World!...... " + i;
System.out.println(" [ Sent ] 消息内容 " + message);
channel.basicPublish(RabbitConfig.FANOUT_EXCHANGE, "", MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
}
channel.close();
connection.close();
}
@GetMapping("/direct")
public void direct() throws IOException, TimeoutException {
Connection connection = RabbitConfig.getConnection();
Channel channel = connection.createChannel();
/*
* 声明 direct 交换机
*/
channel.exchangeDeclare(RabbitConfig.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT, true, false, false, null);
channel.queueDeclare(RabbitConfig.DIRECT_QUEUE_A, true, false, false, null);
channel.queueDeclare(RabbitConfig.DIRECT_QUEUE_B, true, false, false, null);
channel.queueBind(RabbitConfig.DIRECT_QUEUE_A, RabbitConfig.DIRECT_EXCHANGE, "direct.admin");
channel.queueBind(RabbitConfig.DIRECT_QUEUE_B, RabbitConfig.DIRECT_EXCHANGE, "direct.yzm");
for (int i = 1; i <= 10; i++) {
String message = "Hello World! " + i;
if (i % 2 == 0) {
channel.basicPublish(RabbitConfig.DIRECT_EXCHANGE, "direct.admin", null, message.getBytes());
} else {
channel.basicPublish(RabbitConfig.DIRECT_EXCHANGE, "direct.yzm", null, message.getBytes());
}
System.out.println(" [ Sent ] 消息内容 " + message);
}
channel.close();
connection.close();
}
@GetMapping("/topic")
public void topic() throws IOException, TimeoutException {
Connection connection = RabbitConfig.getConnection();
Channel channel = connection.createChannel();
/*
* 声明 topic 交换机
*/
channel.exchangeDeclare(RabbitConfig.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC, true, false, false, null);
channel.queueDeclare(RabbitConfig.TOPIC_QUEUE_A, true, false, false, null);
channel.queueDeclare(RabbitConfig.TOPIC_QUEUE_B, true, false, false, null);
channel.queueDeclare(RabbitConfig.TOPIC_QUEUE_C, true, false, false, null);
channel.queueBind(RabbitConfig.TOPIC_QUEUE_A, RabbitConfig.TOPIC_EXCHANGE, "topic.admin.*");
channel.queueBind(RabbitConfig.TOPIC_QUEUE_B, RabbitConfig.TOPIC_EXCHANGE, "topic.#");
channel.queueBind(RabbitConfig.TOPIC_QUEUE_C, RabbitConfig.TOPIC_EXCHANGE, "topic.*.yzm");
for (int i = 1; i <= 10; i++) {
String message = "Hello World! " + i;
if (i % 3 == 0) {
channel.basicPublish(RabbitConfig.TOPIC_EXCHANGE, "topic.admin.xxx", null, message.getBytes());
} else if (i % 3 == 1) {
channel.basicPublish(RabbitConfig.TOPIC_EXCHANGE, "topic.xxx.xxx", null, message.getBytes());
} else {
channel.basicPublish(RabbitConfig.TOPIC_EXCHANGE, "topic.xxx.yzm", null, message.getBytes());
}
System.out.println(" [ Sent ] 消息内容 " + message);
}
channel.close();
connection.close();
}
@GetMapping("/headers")
public void headers() throws IOException, TimeoutException {
Connection connection = RabbitConfig.getConnection();
Channel channel = connection.createChannel();
/*
* 声明 header 交换机
*/
channel.exchangeDeclare(RabbitConfig.HEADER_EXCHANGE, BuiltinExchangeType.HEADERS, true, false, false, null);
channel.queueDeclare(RabbitConfig.HEADER_QUEUE_A, true, false, false, null);
channel.queueDeclare(RabbitConfig.HEADER_QUEUE_B, true, false, false, null);
Map<String, Object> mapA = new HashMap<>();
mapA.put("x-match", "all"); // 完全匹配
mapA.put("key1", "value1");
mapA.put("name", "yzm");
channel.queueBind(RabbitConfig.HEADER_QUEUE_A, RabbitConfig.HEADER_EXCHANGE, "", mapA);
Map<String, Object> mapB = new HashMap<>();
mapB.put("x-match", "any"); // 匹配任意一个
mapB.put("name", "yzm");
channel.queueBind(RabbitConfig.HEADER_QUEUE_B, RabbitConfig.HEADER_EXCHANGE, "", mapB);
Map<String, Object> headersA = new HashMap<>();
headersA.put("key1", "value1");
headersA.put("name", "yzm");
AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
.headers(headersA)
.build();
System.out.println("生产者:该消息会被1和2打印");
channel.basicPublish(RabbitConfig.HEADER_EXCHANGE, "", basicProperties, "该消息会被1和2打印".getBytes());
/* Map<String, Object> headersB = new HashMap<>();
headersB.put("name", "yzm");
AMQP.BasicProperties basicPropertiesB = new AMQP.BasicProperties.Builder()
.headers(headersB)
.build();
System.out.println("生产者:该消息只会被2打印");
channel.basicPublish(RabbitConfig.HEADER_EXCHANGE, "", basicPropertiesB, "该消息只会被2打印".getBytes());*/
channel.close();
connection.close();
}
}
package com.yzm.rabbitmq_09.receiver;
import com.rabbitmq.client.*;
import com.yzm.rabbitmq_09.config.RabbitConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@RestController
@RequestMapping("/receiver")
public class Receiver {
@GetMapping("/simple")
public void simple() throws IOException {
// 1、获取连接
Connection connection = RabbitConfig.getConnection();
// 2、创建通道
Channel channel = connection.createChannel();
/* 3、消费消息
* String queue 队列名称
* boolean autoAck 自动回复,当消费者接收到消息后要告诉mq消息已接收,如果将此参数设置为tru表示会自动回复mq,如果设置为false要通过编程实现回复
* Consumer consumer,消费方法,当消费者接收到消息要执行的方法
*/
channel.basicConsume(RabbitConfig.QUEUE, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(" [ received@simple_1 ] 消息内容 : " + new String(body, StandardCharsets.UTF_8) + "!");
}
});
//取消自动ack
/* channel.basicConsume(RabbitConfig.QUEUE, false, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(" [ received@simple_2 ] 消息内容 : " + new String(body, StandardCharsets.UTF_8) + "!");
//消息确认
channel.basicAck(envelope.getDeliveryTag(), false);
}
});*/
}
@GetMapping("/fanout")
public void fanout() {
Thread t1 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.FANOUT_QUEUE_A, true, getConsumer(channel, " [ received@fanout_1 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t1");
Thread t2 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.FANOUT_QUEUE_B, true, getConsumer(channel, " [ received@fanout_2 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t2");
t1.start();
t2.start();
}
@GetMapping("/direct")
public void direct() {
Thread t3 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.DIRECT_QUEUE_A, true, getConsumer(channel, " [ received@direct_1 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t3");
Thread t4 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.DIRECT_QUEUE_B, true, getConsumer(channel, " [ received@direct_2 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t4");
t3.start();
t4.start();
}
@GetMapping("/topic")
public void topic() {
Thread t5 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.TOPIC_QUEUE_A, true, getConsumer(channel, " [ received@topic_1 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t5");
Thread t6 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.TOPIC_QUEUE_B, true, getConsumer(channel, " [ received@topic_2 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t6");
Thread t7 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.TOPIC_QUEUE_C, true, getConsumer(channel, " [ received@topic_3 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t7");
t5.start();
t6.start();
t7.start();
}
@GetMapping("/headers")
public void headers() {
Thread t8 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.HEADER_QUEUE_A, true, getConsumer(channel, " [ received@headers_1 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t8");
Thread t9 = new Thread(() -> {
Connection connection = RabbitConfig.getConnection();
Channel channel = null;
try {
channel = connection.createChannel();
channel.basicConsume(RabbitConfig.HEADER_QUEUE_B, true, getConsumer(channel, " [ received@headers_2 ] : "));
} catch (IOException e) {
e.printStackTrace();
}
}, "t9");
t8.start();
t9.start();
}
private DefaultConsumer getConsumer(Channel channel, String s) {
return new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(s + new String(body, StandardCharsets.UTF_8) + "!");
}
};
}
}
http://localhost:8080/sender/simple
http://localhost:8080/receiver/simple
运行结果:
http://localhost:8080/sender/fanout
http://localhost:8080/receiver/fanout
运行结果:
http://localhost:8080/sender/direct
http://localhost:8080/receiver/direct
运行结果:
http://localhost:8080/sender/topic
http://localhost:8080/receiver/topic
运行结果:
http://localhost:8080/sender/headers
http://localhost:8080/receiver/headers
运行结果: