插件开发框架
本文介绍RabbitMQ插件开发框架的核心机制与标准开发流程。
定义
RabbitMQ插件是基于Erlang/OTP架构的扩展模块,通过BEAM虚拟机动态加载,用于扩展消息路由、认证授权、协议适配等功能。
原理
插件加载机制
XML
Broker启动流程:
1. 加载rabbit.app配置
2. 扫描plugins_dir目录下的.esz/.ez包
3. 读取plugin_definitions文件
4. 按依赖关系排序加载
5. 调用application:start/2启动
核心扩展点
| 扩展点 | 用途 | 接口 |
|---|---|---|
| rabbit_auth_mechanism | 自定义认证 | auth_mechanism_behaviour |
| rabbit_exchange_type | 交换机类型 | rabbit_exchange_type_behaviour |
| rabbit_policy_validator | 策略校验 | policy_validator |
示例
环境搭建
erlang
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.20.0</version>
</dependency>
</dependencies>
自定义认证插件(Erlang)
erlang
-module(rabbit_auth_mechanism_custom).
-behaviour(rabbit_auth_mechanism_behaviour).
-export([description/0, response_size/1, init/0,
handle_response/3, login/1]).
description() ->
"Custom authentication mechanism".
response_size(_State) ->
{error, not_supported}.
init() ->
{ok, undefined}.
handle_response(Response, _State, _AuthModules) ->
case validate_credentials(Response) of
true ->
{ok, #user{username = extract_user(Response)}};
false ->
{error, access_refused, "Invalid credentials"}
end.
validate_credentials(Credentials) ->
% 调用外部认证服务
call_auth_service(Credentials).
extract_user(Credentials) ->
binary_to_list(Credentials).
login(_State) ->
{ok, self()}.
插件描述文件(rabbit_auth_custom.erl)
Java
{application, rabbit_auth_custom,
[{description, "Custom Auth Plugin"},
{vsn, "1.0.0"},
{modules, [rabbit_auth_mechanism_custom]},
{registered, []},
{applications, [kernel, stdlib, rabbit]},
{mod, {rabbit_auth_custom_app, []}},
{env, []}]}.
Java客户端调用
Bash
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
public class CustomAuthExample {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(5672);
factory.setVirtualHost("/");
// 设置自定义认证参数
factory.setUsername("admin");
factory.setPassword("secret");
try (Connection connection = factory.newConnection()) {
System.out.println("Connected with custom auth");
}
}
}
编译与部署
text
# 编译插件
rebar3 compile
rebar3 as prod release
# 安装插件
rabbitmq-plugins enable rabbit_auth_custom
# 重启生效
rabbitmqctl stop_app
rabbitmqctl start_app
注意事项
插件依赖必须在plugin_definitions中显式声明,否则加载顺序不确定导致启动失败。
插件代码运行在Broker主进程,异常处理不当会引发整个节点崩溃,务必使用supervisor监控子进程。
热升级插件需保证新旧版本接口兼容,否则需滚动重启集群。
插件日志级别默认info,生产环境建议调整为warning避免磁盘打满。
要点总结
- 插件基于Erlang/OTP应用框架,通过BEAM动态加载
- 核心扩展点包括认证、交换机、策略校验等
- 开发流程:编写模块 -> 定义application -> 编译打包 -> 安装启用
- 异常处理必须严格,避免影响Broker主进程
- 依赖声明与加载顺序是插件稳定性的关键
📝 发现内容有误?点击此处直接编辑