RabbitMQ 入门教程

1. 引言

RabbitMQ 是一个开源的消息代理和队列服务器,实现了 AMQP 0-9-1 标准。本教程将指导你如何使用 Java 和 RabbitMQ 进行消息传递。

2. 安装与配置

2.1 安装 RabbitMQ

1. 下载:

```bash

wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.9.15/rabbitmq-server-generic-unix-3.9.15.tar.xz

```

2. 解压:

```bash

tar xf rabbitmq-server-generic-unix-3.9.15.tar.xz

```

3. 启动服务:

```bash

cd rabbitmq_server-3.9.15

./sbin/rabbitmq-server -detached

```

2.2 配置管理插件

```bash

./sbin/rabbitmq-plugins enable rabbitmq_management

```

3. 创建虚拟主机与用户

```bash

rabbitmqctl add_vhost my_vhost

rabbitmqctl add_user my_user my_password

rabbitmqctl set_permissions -p my_vhost my_user ".*" ".*" ".*"

```

4. Java 客户端环境准备

4.1 添加依赖

```xml

com.rabbitmq

amqp-client

5.13.0

```

5. 生产者与消费者模型

5.1 发布/订阅 (Fanout)

5.1.1 Fanout Exchange

```java

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

public class FanoutExchange {

private final static String EXCHANGE_NAME = "logs";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

// Send

String message = "Hello World!";

channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));

System.out.println(" [x] Sent '" + message + "'");

}

}

}

```

5.1.2 Fanout Consumer

```java

import com.rabbitmq.client.*;

public class FanoutConsumer {

private final static String EXCHANGE_NAME = "logs";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

// Declare a random queue

String queueName = channel.queueDeclare().getQueue();

// Bind the queue to the exchange

channel.queueBind(queueName, EXCHANGE_NAME, "");

System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

DeliverCallback deliverCallback = (consumerTag, delivery) -> {

String message = new String(delivery.getBody(), "UTF-8");

System.out.println(" [x] Received '" + message + "'");

};

channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});

}

}

}

```

6. 工作队列 (Work Queues)

6.1 Work Queue Producer

```java

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

public class WorkQueueProducer {

private final static String QUEUE_NAME = "work_queue";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.queueDeclare(QUEUE_NAME, true, false, false, null);

String message = "Task message";

channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));

System.out.println(" [x] Sent '" + message + "'");

}

}

}

```

6.2 Work Queue Consumer

```java

import com.rabbitmq.client.*;

public class WorkQueueConsumer {

private final static String QUEUE_NAME = "work_queue";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.queueDeclare(QUEUE_NAME, true, false, false, null);

System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

DeliverCallback deliverCallback = (consumerTag, delivery) -> {

String message = new String(delivery.getBody(), "UTF-8");

System.out.println(" [x] Received '" + message + "'");

try {

doWork(message);

} finally {

System.out.println(" [x] Done");

channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

}

};

channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {});

}

}

private static void doWork(String task) {

for (char ch : task.toCharArray()) {

if (ch == '.') {

try {

Thread.sleep(1000);

} catch (InterruptedException _ignored) {

Thread.currentThread().interrupt();

}

}

}

}

}

```

7. 路由 (Routing)

7.1 Direct Exchange Producer

```java

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

public class DirectExchangeProducer {

private final static String EXCHANGE_NAME = "direct_logs";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.exchangeDeclare(EXCHANGE_NAME, "direct");

String severity = getSeverity(argv);

String message = getMessage(argv);

channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes("UTF-8"));

System.out.println(" [x] Sent '" + severity + "':'" + message + "'");

}

}

private static String getSeverity(String[] strings) {

if (strings.length < 1)

return "info";

return strings[0];

}

private static String getMessage(String[] strings) {

if (strings.length < 2)

return "Hello World!";

return joinStrings(strings, " ", 1);

}

private static String joinStrings(String[] strings, String delimiter, int startIndex) {

int length = strings.length;

if (length == 0 || length

return "";

StringBuilder words = new StringBuilder(strings[startIndex]);

for (int i = startIndex + 1; i < length; i++) {

words.append(delimiter).append(strings[i]);

}

return words.toString();

}

}

```

7.2 Direct Exchange Consumers

```java

import com.rabbitmq.client.*;

public class DirectExchangeConsumer {

private final static String EXCHANGE_NAME = "direct_logs";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.exchangeDeclare(EXCHANGE_NAME, "direct");

String severity = getSeverity(argv);

String queueName = channel.queueDeclare().getQueue();

channel.queueBind(queueName, EXCHANGE_NAME, severity);

System.out.println(" [*] Waiting for messages in '" + severity + "'. To exit press CTRL+C");

DeliverCallback deliverCallback = (consumerTag, delivery) -> {

String message = new String(delivery.getBody(), "UTF-8");

System.out.println(" [x] Received '" + message + "'");

};

channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});

}

}

private static String getSeverity(String[] strings) {

if (strings.length < 1)

return "info";

return strings[0];

}

}

```

8. 主题交换机 (Topic Exchanges)

8.1 Topic Exchange Producer

```java

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

public class TopicExchangeProducer {

private final static String EXCHANGE_NAME = "topic_logs";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.exchangeDeclare(EXCHANGE_NAME, "topic");

String routingKey = getRoutingKey(argv);

String message = getMessage(argv);

channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));

System.out.println(" [x] Sent routingKey:'" + routingKey + "' message:'" + message + "'");

}

}

private static String getRoutingKey(String[] strings) {

if (strings.length < 1)

return "anonymous.info";

return strings[0];

}

private static String getMessage(String[] strings) {

if (strings.length < 2)

return "Hello World!";

return joinStrings(strings, " ", 1);

}

private static String joinStrings(String[] strings, String delimiter, int startIndex) {

int length = strings.length;

if (length == 0 || length

return "";

StringBuilder words = new StringBuilder(strings[startIndex]);

for (int i = startIndex + 1; i < length; i++) {

words.append(delimiter).append(strings[i]);

}

return words.toString();

}

}

```

8.2 Topic Exchange Consumers

```java

import com.rabbitmq.client.*;

public class TopicExchangeConsumer {

private final static String EXCHANGE_NAME = "topic_logs";

public static void main(String[] argv) throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

try (Connection connection = factory.newConnection();

Channel channel = connection.createChannel()) {

channel.exchangeDeclare(EXCHANGE_NAME, "topic");

String bindingKey = getBindingKey(argv);

String queueName = channel.queueDeclare().getQueue();

channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);

System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

DeliverCallback deliverCallback = (consumerTag, delivery) -> {

String message = new String(delivery.getBody(), "UTF-8");

System.out.println(" [x] Received '" + message + "'");

};

channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});

}

}

private static String getBindingKey(String[] strings) {

if (strings.length < 1)

return "anonymous.info";

return strings[0];

}

}

你可能感兴趣的:(ruby,开发语言,后端)