Elixir 版 RabbitMQ 官方教程实战:用 mix run 跑通 Hello World、工作队列、发布订阅、路由、主题与 RPC 六大示例

原创2026-10-14 11:46:511,820 阅读
文章标签:示例工程

Elixir 版 RabbitMQ 官方教程实战:用 mix run 跑通 Hello World、工作队列、发布订阅、路由、主题与 RPC 六大示例

本指南以仓库中 elixir/README.md 为主线,完整介绍如何使用 Elixir 语言与 amqp 客户端逐步实现 RabbitMQ 官方六步教程(Hello World、Work Queues、Publish/Subscribe、Routing、Topics、RPC)。读完本文,你将掌握从环境搭建、依赖安装到六个可运行示例的完整命令,并能从 elixir/ 目录下的源码入手,理解 AMQP.Connection、AMQP.Channel、AMQP.Queue、AMQP.Exchange、AMQP.Basic 等核心模块的实际调用方式,具备在 Elixir 项目中自主使用 RabbitMQ 的能力。

环境准备:Elixir、Mix 与 amqp 客户端

需要安装的软件

运行这些示例,需要一台安装了较新版本 Elixir 的机器。Elixir 发行版通常自带 Mix 构建工具(mix 命令),它负责依赖解析、编译与项目任务管理,是后续 mix run、mix deps.get 的基础。此外还需要一个可访问的 RabbitMQ 服务端(本地默认 localhost:5672)。

在仓库中,Elixir 教程工程由 elixir/mix.exs 定义,其中明确了版本约束:

def project do
  [app: :rabbitmq_tutorials,
   version: "1.0.0",
   elixir: "~> 1.5",
   build_embedded: Mix.env == :prod,
   start_permanent: Mix.env == :prod,
   deps: deps()]
end

可以看到工程要求 Elixir ~> 1.5 及以上,因此任何主流的现代 Elixir 版本(1.5 之后的小版本升级均兼容)都可以直接运行。

依赖:基于 Erlang 客户端的 amqp 包

教程使用的消息客户端是 Elixir AMQP 0-9-1 客户端(Hex 包 :amqp),它构建在官方 RabbitMQ Erlang 客户端之上,因此在 Elixir 中暴露的 API 与 Erlang 客户端一一对应,但又以 Elixir 惯用的命名(如 AMQP.Connection.open/0)呈现。

依赖声明位于 elixir/mix.exs:

defp deps do
  [
    {:amqp, "~> 4.1"},
  ]
end

同时,工程把 :amqp 声明为 OTP 应用启动依赖(elixir/mix.exs):

def application do
  [applications: [:amqp]]
end

这一行非常关键:它保证在 mix run 启动脚本前,amqp 应用已被自动启动,脚本内才能直接调用 AMQP.Connection.open 而不必手动 Application.ensure_all_started(:amqp)。

elixir/config/config.exs 目前仅有一行 import Config,没有任何自定义配置,说明所有运行参数都走 amqp 客户端的默认值(默认连接本机、默认账号 guest/guest)。

安装并编译依赖

按照 elixir/README.md 的说明,进入 elixir/ 目录后执行:

mix deps.get
mix deps.compile
  • mix deps.get:从 Hex 拉取 amqp 及其传递依赖,生成 mix.lock;
  • mix deps.compile:编译依赖,使 AMQP 模块在后续 mix run 中可用。

两步执行成功后即可运行教程脚本。

统一运行方式:mix run

文档明确要求使用 mix run 运行示例。mix run 会先启动当前 OTP 应用(进而启动 :amqp),再执行传入的 .exs 脚本文件,因此脚本内可以直接编写过程式代码,无需手动启动应用。

以 elixir/send.exs 为例,可以看到所有示例共用的代码骨架:

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)
# ... 声明队列/交换机、发布或消费 ...
AMQP.Connection.close(connection)

AMQP.Connection.open/0 返回 {:ok, connection} 元组,AMQP.Channel.open/1 在连接上打开信道(Channel),之后所有队列、交换机、发布、消费操作都在该信道上进行。消费者脚本(如 receive.exs)则用 Elixir 进程的 receive 阻塞等待 {:basic_deliver, payload, meta} 消息,这正是 Elixir/Erlang 消息传递机制与 RabbitMQ 投递事件的天然融合。

教程一:Hello World——最简单的发送与接收

第一个教程演示最基础的「单生产者、单消费者」模型。先启动消费者,再启动生产者:

mix run receive.exs
mix run send.exs

生产者 elixir/send.exs

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)
AMQP.Queue.declare(channel, "hello", durable: true, arguments: [{"x-queue-type", :longstr, "quorum"}])
AMQP.Basic.publish(channel, "", "hello", "Hello World!")
IO.puts " [x] Sent 'Hello World!'"
AMQP.Connection.close(connection)

关键点:

  • AMQP.Queue.declare/3 声明名为 hello 的队列;注意这里传入了 durable: true 与 arguments: [{"x-queue-type", :longstr, "quorum"}],即把队列声明为持久化的 quorum 队列(RabbitMQ 3.8 引入的复制队列类型,需要服务端支持)。这是仓库当前实现相对经典教程的演进,能获得更高可用性。
  • AMQP.Basic.publish(channel, "", "hello", "Hello World!"):向默认交换机(空字符串 "",即 direct 类型的默认 exchange)发布消息,路由键为 hello,消息会进入同名队列。
  • 发送完成后立即 AMQP.Connection.close(connection) 关闭连接。

消费者 elixir/receive.exs

defmodule Receive do
  def wait_for_messages do
    receive do
      {:basic_deliver, payload, _meta} ->
        IO.puts " [x] Received #{payload}"
        wait_for_messages()
    end
  end
end

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)
AMQP.Queue.declare(channel, "hello", durable: true, arguments: [{"x-queue-type", :longstr, "quorum"}])
AMQP.Basic.consume(channel, "hello", nil, no_ack: true)
IO.puts " [*] Waiting for messages. To exit press CTRL+C, CTRL+C"

Receive.wait_for_messages()

关键点:

  • 消费者同样先 declare 队列(幂等,若已存在则无副作用),保证队列在消费前一定存在。
  • AMQP.Basic.consume(channel, "hello", nil, no_ack: true) 开始消费,no_ack: true 表示自动确认。
  • 模块内的 wait_for_messages/0 用 receive 循环接收 {:basic_deliver, payload, _meta} 模式的消息并打印,实现持续监听;按 CTRL+C 退出。

教程二:Work Queues——任务分发与公平调度

第二个教程解决「任务较重、需要多个消费者分担」的场景。生产者把任务(带有点号后缀的文本)发往持久化队列,多个消费者争抢处理,处理耗时按点号数量模拟。

mix run worker.exs
mix run new_task.exs

生产者 elixir/new_task.exs

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)

AMQP.Queue.declare(channel, "task_queue", durable: true, arguments: [{"x-queue-type", :longstr, "quorum"}])

message =
  case System.argv do
    []    -> "Hello World!"
    words -> Enum.join(words, " ")
  end

AMQP.Basic.publish(channel, "", "task_queue", message, persistent: true)
IO.puts " [x] Sent '#{message}'"
AMQP.Connection.close(connection)

关键点:

  • task_queue 同样声明为持久化 quorum 队列。
  • 命令行参数通过 System.argv 收集,多个单词用空格连接成完整消息;无参数时默认 "Hello World!"。
  • 发布时带 persistent: true 标记消息持久化,配合持久化队列防止 RabbitMQ 重启后消息丢失。

消费者 elixir/worker.exs

defmodule Worker do
  def wait_for_messages(channel) do
    receive do
      {:basic_deliver, payload, meta} ->
        IO.puts " [x] Received #{payload}"
        payload
        |> to_charlist
        |> Enum.count(fn x -> x == ?. end)
        |> Kernel.*(1000)
        |> :timer.sleep
        IO.puts " [x] Done."
        AMQP.Basic.ack(channel, meta.delivery_tag)
        wait_for_messages(channel)
    end
  end
end

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)

AMQP.Queue.declare(channel, "task_queue", durable: true, arguments: [{"x-queue-type", :longstr, "quorum"}])
AMQP.Basic.qos(channel, prefetch_count: 1)

AMQP.Basic.consume(channel, "task_queue")
IO.puts " [*] Waiting for messages. To exit press CTRL+C, CTRL+C"

Worker.wait_for_messages(channel)

关键点:

  • 模拟耗时:统计 payload 中 . 的数量 × 1000 毫秒后 :timer.sleep,即一个点睡 1 秒。
  • AMQP.Basic.qos(channel, prefetch_count: 1):设置预取计数为 1,即每个消费者同一时刻最多接收一条未确认消息,实现「能者多劳」的公平分发(fair dispatch),避免任务都堆积给某一个消费者。
  • 处理完成后 AMQP.Basic.ack(channel, meta.delivery_tag) 手动确认消息;消费时未指定 no_ack(默认手动确认),因此即使消费者中途崩溃,未确认消息也会重新投递。

教程三:Publish/Subscribe——fanout 广播

第三个教程引入交换机(Exchange)概念,使用 fanout 类型的交换机把每条消息广播给所有绑定的队列。

mix run receive_logs.exs
mix run emit_log.exs

生产者 elixir/emit_log.exs

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)

message =
  case System.argv do
    []    -> "Hello World!"
    words -> Enum.join(words, " ")
  end

AMQP.Exchange.declare(channel, "logs", :fanout)
AMQP.Basic.publish(channel, "logs", "", message)
IO.puts " [x] Sent '#{message}'"
AMQP.Connection.close(connection)

关键点:

  • AMQP.Exchange.declare(channel, "logs", :fanout) 声明名为 logs、类型为 fanout 的交换机;重复声明同名同类型交换机是幂等操作。
  • 发布时指定交换机为 "logs",路由键为空字符串——fanout 交换机忽略路由键,向所有绑定队列广播。

消费者 elixir/receive_logs.exs

defmodule ReceiveLogs do
  def wait_for_messages(channel) do
    receive do
      {:basic_deliver, payload, _meta} ->
        IO.puts " [x] Received #{payload}"
        wait_for_messages(channel)
    end
  end
end

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)

AMQP.Exchange.declare(channel, "logs", :fanout)
{:ok, %{queue: queue_name}} = AMQP.Queue.declare(channel, "", exclusive: true)
AMQP.Queue.bind(channel, queue_name, "logs")
AMQP.Basic.consume(channel, queue_name, nil, no_ack: true)
IO.puts " [*] Waiting for messages. To exit press CTRL+C, CTRL+C"

ReceiveLogs.wait_for_messages(channel)

关键点:

  • AMQP.Queue.declare(channel, "", exclusive: true):声明临时独占队列(空队列名由服务端生成),消费者退出即自动删除,每个消费者拥有独立队列。
  • AMQP.Queue.bind(channel, queue_name, "logs"):把临时队列绑定到 logs 交换机,此后广播消息会投递到该队列。

教程四:Routing——direct 交换机与路由键

第四个教程使用 direct 交换机,让消费者只接收自己关心的特定严重级别(severity)日志。命令行通过 --info、--warning、--error 开关选择关心的级别。

mix run receive_logs_direct.exs --info --warning
mix run emit_log_direct.exs --info "A message"

参数解析:OptionParser

收发双方都用 Elixir 标准库 OptionParser.parse/2 解析命令行开关(elixir/emit_log_direct.exs、elixir/receive_logs_direct.exs):

System.argv
|> OptionParser.parse(strict: [info:    :boolean,
                               warning: :boolean,
                               error:   :boolean])

strict 选项限定只接受这三个布尔开关;解析结果形如 {[info: true, warning: false, error: false], ["A message"], []},其中第一项为开关列表,第二项为位置参数(消息正文)。

生产者 elixir/emit_log_direct.exs

{severities, raw_message, _} =
  System.argv
  |> OptionParser.parse(strict: [info:    :boolean,
                                 warning: :boolean,
                                 error:   :boolean])
  |> case do
    {[], msg, _} -> {[info: true], msg, []}
    other -> other
  end

message =
  case raw_message do
    []    -> "Hello World!"
    words -> Enum.join(words, " ")
  end

AMQP.Exchange.declare(channel, "direct_logs", :direct)

for {severity, true} <- severities do
  severity = severity |> to_string
  AMQP.Basic.publish(channel, "direct_logs", severity, message)
  IO.puts " [x] Sent '[#{severity}] #{message}'"
end

AMQP.Connection.close(connection)

关键点:

  • 无任何开关时默认按 info 级别发送({[], msg, _} -> {[info: true], msg, []})。
  • 声明 direct_logs 为 :direct 类型交换机。
  • 遍历所有为 true 的严重级别,把原子转成字符串作为路由键发布,因此 --info --warning 会各发一条消息,路由键分别为 info 与 warning。

消费者 elixir/receive_logs_direct.exs

{:ok, %{queue: queue_name}} = AMQP.Queue.declare(channel, "", exclusive: true)

for {severity, true} <- severities do
  binding_key = severity |> to_string
  AMQP.Queue.bind(channel, queue_name, "direct_logs", routing_key: binding_key)
end

AMQP.Basic.consume(channel, queue_name, nil, no_ack: true)

关键点:

  • 为每个选中的严重级别创建一条绑定(binding):AMQP.Queue.bind/4 通过 routing_key 指定绑定键,direct 交换机只把路由键完全等于绑定键的消息投递到对应队列。
  • 消费回调打印时通过 meta.routing_key 显示消息实际携带的路由键(elixir/receive_logs_direct.exs)。

教程五:Topics——按模式匹配的主题路由

第五个教程用 topic 交换机实现「按绑定键模式」过滤消息。绑定键支持通配符:* 匹配一个单词,# 匹配零个或多个单词,消息路由键由点号分隔的多个单词组成。

mix run receive_logs_topic.exs "info.*" "warn.*"
mix run emit_log_topic.exs "info.connections" "Connected"

生产者 elixir/emit_log_topic.exs

{topic, message} =
  System.argv
  |> case do
    []            -> {"anonymous.info", "Hello World!"}
    [message]     -> {"anonymous.info", message}
    [topic|words] -> {topic, Enum.join(words, " ")}
  end

AMQP.Exchange.declare(channel, "topic_logs", :topic)

AMQP.Basic.publish(channel, "topic_logs", topic, message)
IO.puts " [x] Sent '[#{topic}] #{message}'"
AMQP.Connection.close(connection)

关键点:

  • 命令行第一个参数作为主题(路由键),其余单词拼成消息正文;无参数默认主题 anonymous.info、消息 "Hello World!"。
  • 声明 topic_logs 为 :topic 类型交换机,发布时指定主题作为路由键。

消费者 elixir/receive_logs_topic.exs

if length(System.argv) == 0 do
  IO.puts "Usage: mix run receive_logs_topic.exs [binding_key]..."
  System.halt(1)
end
for binding_key <- System.argv do
  AMQP.Queue.bind(channel, queue_name, "topic_logs", routing_key: binding_key)
end

关键点:

  • 消费者必须提供至少一个绑定键,否则打印用法说明并以状态码 1 退出(System.halt(1)),避免无意义的空绑定。
  • 多个绑定键通过多个 AMQP.Queue.bind 依次绑定到同一临时队列上;例如 "info.*" 会匹配 info.connections、info.warn 等两个单词的主题,而 "warn.*" 匹配 warn.* 系列。

教程六:RPC——基于 reply_to 与 correlation_id 的远程调用

第六个教程实现经典 RPC 模式:客户端把请求发到 rpc_queue 并等待响应,服务端计算斐波那契数后把结果发回客户端指定的回调队列。

mix run rpc_server.exs
mix run rpc_client.exs

服务端 elixir/rpc_server.exs

defmodule FibServer do
  def fib(n), do: fib(n, 0, 1)
  defp fib(0, a, _b), do: a
  defp fib(n, a, b) when n > 0, do: fib(n - 1, b, a + b)

  def wait_for_messages(channel) do
    receive do
      {:basic_deliver, payload, meta} ->
        {n, _} = Integer.parse(payload)
        IO.puts " [.] fib(#{n})"
        response = fib(n)

        AMQP.Basic.publish(channel, "", meta.reply_to, "#{response}", correlation_id: meta.correlation_id)
        AMQP.Basic.ack(channel, meta.delivery_tag)

        wait_for_messages(channel)
    end
  end
end

{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)

AMQP.Queue.declare(channel, "rpc_queue", durable: true, arguments: [{"x-queue-type", :longstr, "quorum"}])
AMQP.Basic.qos(channel, prefetch_count: 1)
AMQP.Basic.consume(channel, "rpc_queue")

IO.puts " [x] Awaiting RPC requests"
FibServer.wait_for_messages(channel)

关键点:

  • FibServer.fib/1 用尾递归实现斐波那契数列(fib(n) = fib(n, 0, 1) 迭代形式)。
  • 收到请求后,通过 meta.reply_to(客户端指定的回调队列名)发布响应,并回传 correlation_id: meta.correlation_id,使客户端能识别哪条响应对应哪个请求;随后手动 ack。
  • rpc_queue 声明为持久化 quorum 队列,并设置 prefetch_count: 1 保证每个请求被串行处理。

客户端 elixir/rpc_client.exs

defmodule FibonacciRpcClient do
  def wait_for_messages(_channel, correlation_id) do
    receive do
      {:basic_deliver, payload, %{correlation_id: ^correlation_id}} ->
        {n, _} = Integer.parse(payload)
        n
    end
  end

  def call(n) do
    {:ok, connection} = AMQP.Connection.open
    {:ok, channel} = AMQP.Channel.open(connection)

    {:ok, %{queue: queue_name}} = AMQP.Queue.declare(channel, "", exclusive: true)
    AMQP.Basic.consume(channel, queue_name, nil, no_ack: true)
    correlation_id = :erlang.unique_integer |> :erlang.integer_to_binary |> Base.encode64
    request = to_string(n)
    AMQP.Basic.publish(channel, "", "rpc_queue", request, reply_to: queue_name, correlation_id: correlation_id)

    FibonacciRpcClient.wait_for_messages(channel, correlation_id)
  end
end

num =
  case System.argv do
    []    -> 30
    param ->
      {x, _} =
        param
        |> Enum.join(" ")
        |> Integer.parse
      x
  end

IO.puts " [x] Requesting fib(#{num})"
response = FibonacciRpcClient.call(num)
IO.puts " [.] Got #{response}"

关键点:

  • 客户端声明临时独占回调队列,并在该队列上消费(no_ack: true)。
  • correlation_id 由 :erlang.unique_integer 生成唯一整数后转二进制再 Base.encode64 得到,保证每个请求唯一。
  • 发布请求时通过 reply_to: queue_name 告知服务端响应发往何处,correlation_id: correlation_id 用于匹配。
  • wait_for_messages/2 用 receive 模式匹配 %{correlation_id: ^correlation_id}(pin 操作符),只接受与本次请求 ID 一致的响应,忽略其他消息。
  • 命令行参数缺省时默认请求 fib(30);运行结果会打印请求与响应值。

总结:RabbitMQ 核心概念与 Elixir API 对照

六个教程覆盖了 RabbitMQ 最核心的编程模型,汇总如下:

教程 交换机类型 关键机制 代表 API
Hello World 默认交换机 队列声明、自动确认 AMQP.Queue.declare/3、AMQP.Basic.publish/4、AMQP.Basic.consume/4
Work Queues 默认交换机 持久化队列、prefetch、手动 ack AMQP.Basic.qos/2、AMQP.Basic.ack/2
Publish/Subscribe :fanout 临时独占队列、队列绑定交换机 AMQP.Exchange.declare/3、AMQP.Queue.bind/3
Routing :direct 路由键精确匹配 AMQP.Queue.bind/4(带 routing_key)
Topics :topic 绑定键通配符匹配(*、#) AMQP.Queue.bind/4(带模式绑定键)
RPC 默认交换机 回调队列、reply_to、correlation_id AMQP.Basic.publish/6、receive 模式匹配

从仓库源码可以总结出 Elixir 使用 RabbitMQ 的通用流程:AMQP.Connection.open 建立连接 → AMQP.Channel.open 打开信道 → 声明交换机与队列(elixir/emit_log.exs、elixir/send.exs)→ 发布(AMQP.Basic.publish)或消费(AMQP.Basic.consume + receive 循环)。消费者侧普遍利用 Elixir 进程邮箱的 receive 模式匹配机制接收 {:basic_deliver, payload, meta} 元组,配合 meta 中的 delivery_tag、routing_key、reply_to、correlation_id 等字段实现确认、路由感知与 RPC 关联。每个示例都可以对照 elixir/ 目录下的同名 .exs 文件直接运行、修改与验证,是学习 RabbitMQ 概念与 Elixir 客户端 API 的最佳入门材料。

登录后查看全文
rabbitmq-tutorials