赞
踩
RabbitMQ根据exchange的类型规则将消息路由到相应的queue,其中exchange的类型包括direct,topic,fanout以及headers,我们这里主要介绍topic exchange类型的消息路由原理,其他exchange的路由原理相对简单。Topic exchange的示意图如下:
这里的使用原理不做介绍,主要介绍RabbitMQ源码内部的实现,即exchange和queue如何进行binding的。
1. exchange与queue的binding
RabbitMQ的exchange和queue的binding代码流程如下:
对于RabbitMQ的使用流程一般为:
其中exchange与queue的binding便位于第4个步骤,入口代码如下:
- %% rabbit_channel.erl
- %% 处理将交换机exchange和队列进行绑定的消息
- handle_method(#'queue.bind'{queue = QueueNameBin,
- exchange = ExchangeNameBin,
- routing_key = RoutingKey,
- nowait = NoWait,
- arguments = Arguments}, _, State) ->
- binding_action(fun rabbit_binding:add/2,
- ExchangeNameBin, queue, QueueNameBin, RoutingKey, Arguments,
- #'queue.bind_ok'{}, NoWait, State);
在binding_action函数的一些合法性校验之后,执行真正的binding函数rabbit_binding:add/2。
- %% rabbit_binding.erl
- %% 增加新的绑定
- add(Binding, InnerFun) ->
- binding_action(
- Binding,
- %% Src,Dst都是从mnesia数据库中读取到的数据
- fun (Src, Dst, B) ->
- %% 找到对应交换机的处理模块去验证绑定的合法性(Src必须是exchange交换机类型)
- case rabbit_exchange:validate_binding(Src, B) of
- ok ->
- %% this argument is used to check queue exclusivity(排他性);
- %% in general, we want to fail on that in preference to
- %% anything else
- %% 功效一:检查队列字段exclusive_owner字段的正确性,检查排他性队列(如果一个队列被声明为排他队列,该队列仅对首次声明它的连接可见)
- case InnerFun(Src, Dst) of
- ok ->
- %% 查看rabbit_route表中是否有B这个数据,如果没有则添加到mnesia数据库表中
- case mnesia:read({rabbit_route, B}) of
- %% 增加绑定的实际操作(实际操作mnesia数据库表的函数)
- [] -> add(Src, Dst, B);
- [_] -> fun () -> ok end
- end;
- {error, _} = Err ->
- rabbit_misc:const(Err)
- end;
- {error, _} = Err ->
- rabbit_misc:const(Err)
- end
- end, fun not_found_or_absent_errs/1).
在对应的exchange类型中校验其合法性,校验正常后,需要读取mnesia数据库中rabbit_route表中数据,查看是否有相应的binding信息,如果有则不再进行binding,没有则进行binding操作,判断rabbit_route表数据的原因是:不管exchange和queue是否需要持久化,最后都会将其binding信息写入到rabbit_route表中。
这里提一下,RabbitMQ所保存的一些metadata信息依赖于mnesia分布式数据库,其中RabbitMQ所使用的表可以通过以下命令进行显示:
- [root@master scripts]# ./rabbitmqctl eval 'mnesia:info().'
- ……
- ===> System info in version "4.16", debug level = none <===
- opt_disc. Directory "/var/lib/rabbitmq/mnesia/rabbit@master" is used.
- use fallback at restart = false
- running db nodes = [rabbit@master]
- stopped db nodes = []
- master node tables = []
- remote = []
- ram_copies = [gm_group,mirrored_sup_childspec,rabbit_exchange,
- rabbit_exchange_serial,
- rabbit_exchange_type_consistent_hash,
- rabbit_exchange_type_consistent_hash_ring_state,
- rabbit_listener,rabbit_queue,rabbit_reverse_route,
- rabbit_route,rabbit_semi_durable_route,
- rabbit_topic_trie_binding,rabbit_topic_trie_edge,
- rabbit_topic_trie_node,rh_exchange_table,
- tracked_connection_on_node_rabbit@master,
- tracked_connection_per_vhost_on_node_rabbit@master,
- x_jms_topic_table]
- disc_copies = [rabbit_durable_exchange,rabbit_durable_queue,
- rabbit_durable_route,rabbit_runtime_parameters,
- rabbit_topic_permission,rabbit_user,
- rabbit_user_permission,rabbit_vhost,schema]
- disc_only_copies = []
- [{rabbit@master,disc_copies}] = [rabbit_runtime_parameters,
- rabbit_durable_exchange,rabbit_durable_queue,
- rabbit_user,rabbit_durable_route,
- rabbit_topic_permission,rabbit_vhost,schema,
- rabbit_user_permission]
- [{rabbit@master,ram_copies}] = [rabbit_topic_trie_node,
- tracked_connection_per_vhost_on_node_rabbit@master,
- x_jms_topic_table,
- rabbit_exchange_type_consistent_hash_ring_state,
- rabbit_reverse_route,
- rabbit_topic_trie_binding,
- rabbit_exchange_type_consistent_hash,gm_group,
- rabbit_listener,mirrored_sup_childspec,
- rabbit_exchange,rabbit_route,
- rabbit_exchange_serial,
- tracked_connection_on_node_rabbit@master,
- rabbit_semi_durable_route,rh_exchange_table,
- rabbit_queue,rabbit_topic_trie_edge]
- 21 transactions committed, 7 aborted, 0 restarted, 0 logged to disc
- 0 held locks, 0 in queue; 0 local transactions, 0 remote
- 0 transactions waits for other nodes: []
- ok
其中disc_copies表示会将数据存入磁盘和内存,ram_copies表示将数据存入内存。disc_only_copies表示将数据只存入磁盘。由于mnesia底层是基于ets和dets实现,所以可以通过ets或者dets查看表中数据,注意ets和dets是只能查询本节点的表数据信息。如查看rabbit_exchang表数据信息:
- [root@master scripts]# ./rabbitmqctl eval 'ets:tab2list(rabbit_exchange).'
- [{exchange,{resource,<<"/">>,exchange,<<"amq.direct">>},
- direct,true,false,false,[],undefined,undefined,undefined,
- {[],[rabbit_event_exchange_decorator]},
- #{}},
- ……
- {exchange,{resource,<<"/">>,exchange,<<"amq.headers">>},
- headers,true,false,false,[],undefined,undefined,undefined,
- {[],[rabbit_event_exchange_decorator]},
- #{}}]
具体参看erlang官方文档的mnesia,ets和dets的使用说明。继续回到binding操作,假设第一次进行binding操作,则将执行下列操作:
- %% rabbit_binding.erl
- %% 增加绑定的实际操作(实际操作mnesia数据库表的函数)
- add(Src, Dst, B) ->
- [SrcDurable, DstDurable] = [durable(E) || E <- [Src, Dst]],
- case (SrcDurable andalso DstDurable andalso
- mnesia:read({rabbit_durable_route, B}) =/= []) of
- false -> %% 根据交换机exchange和队列的持久化状态,将路由信息写入mnesia数据库表
- ok = sync_route(#route{binding = B}, SrcDurable, DstDurable,
- fun mnesia:write/3),
- %% 交换机exchange创建后的回调
- x_callback(transaction, Src, add_binding, B),
- %% 让Src对应的exchange交换机类型对应的模块和所有的修饰模块回调serialise_events函数,如果执行成功,则将XName在rabbit_exchange_serial表中的next值加一
- Serial = rabbit_exchange:serial(Src),
- fun () ->
- x_callback(Serial, Src, add_binding, B),
- %% 向rabbit_event事件中心发布绑定信息被创建的事件
- ok = rabbit_event:notify(binding_created, info(B))
- end;
- true -> rabbit_misc:const({error, binding_not_found})
- end.
sync_route函数将exchange和queue的binding信息根据exchange和queue是否持久化来判断是否写入rabbit_durable_route和rabbit_semi_durable_route表中,但无论是否持久化都会写入rabbit_route和rabbit_reverse_route表中。即
除了binding信息写入上述表以外,对于类型为topic的exchange,RabbitMQ还会将binding信息写入rabbit_topic_trie_node,rabbit_topic_trie_edge和rabbit_topic_trie_binding表中。
- %% rabbit_exchange_type_topic.erl
- %% 路由绑定信息的添加回调该模块进行相关的处理(transaction:事务)
- add_binding(transaction, _Exchange, Binding) ->
- internal_add_binding(Binding);
-
- %% rabbit_exchange_type_topic.erl
- %% exchange交换机内部添加绑定信息的接口
- internal_add_binding(#binding{source = X, key = K, destination = D,
- args = Args}) ->
- %% 创建新的节点和边
- FinalNode = follow_down_create(X, split_topic_key(K)),
- %% 创建绑定信息
- trie_add_binding(X, FinalNode, D, Args),
- ok.
其内部原理可参考以下链接:https://www.erlang-solutions.com/blog/rabbit-s-anatomy-understanding-topic-exchanges.html
再提一下,我们执行rabbitmqctl list_bindings命令时,查看到的exchange和queue的bindings信息是从rabbit_route表中进行获取的。即
- %% rabbit_binding.erl
- %% 列出VHostPath下的所有路由绑定信息
- list(VHostPath) ->
- VHostResource = rabbit_misc:r(VHostPath, '_'),
- Route = #route{binding = #binding{source = VHostResource,
- destination = VHostResource,
- _ = '_'},
- _ = '_'},
- [B || #route{binding = B} <- mnesia:dirty_match_object(rabbit_route,
- Route)].
2. 总结
1 RabbitMQ的exchange和queue的binding的建立在客户端与RabbitMQ之间建立连接且exchange和queue创建完成后。
2 binding信息会被保存到mnesia数据库中,其保存的表为rabbit_route表,根据exchange和queue是否持久化判断是否保存到rabbit_durable_route和rabbit_semi_durable_route表中。
3 对于topic类型的exchange,其binding信息还会被保存到rabbit_topic_trie_node,rabbit_topic_trie_edge和rabbit_topic_trie_binding表中。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。