Topics

(using the .NET client)

Prerequisites

This tutorial assumes RabbitMQ isinstalled and running on localhoston standard port (5672). In case you use a different host, port or credentials, connections settings would require adjusting.

Where to get help

If you're having trouble going through this tutorial you can contact usthrough the mailing list.

In the previous tutorial we improved our logging system. Instead of using a fanout exchange only capable of dummy broadcasting, we used a directone, and gained a possibility of selectively receiving the logs.

Although using the direct exchange improved our system, it still has limitations - it can't do routing based on multiple criteria.

In our logging system we might want to subscribe to not only logs based on severity, but also based on the source which emitted the log. You might know this concept from the syslog unix tool, which routes logs based on both severity (info/warn/crit...) and facility (auth/cron/kern...).

That would give us a lot of flexibility - we may want to listen to just critical errors coming from 'cron' but also all logs from 'kern'.

To implement that in our logging system we need to learn about a more complex topicexchange.

Topic exchange

Messages sent to a topic exchange can't have an arbitrary routing_key - it must be a list of words, delimited by dots. The words can be anything, but usually they specify some features connected to the message. A few valid routing key examples: "stock.usd.nyse", "nyse.vmw", "quick.orange.rabbit". There can be as many words in the routing key as you like, up to the limit of 255 bytes.

The binding key must also be in the same form. The logic behind the topic exchange is similar to a direct one - a message sent with a particular routing key will be delivered to all the queues that are bound with a matching binding key. However there are two important special cases for binding keys:

  • * (star) can substitute for exactly one word.
  • # (hash) can substitute for zero or more words.

It's easiest to explain this in an example:

In this example, we're going to send messages which all describe animals. The messages will be sent with a routing key that consists of three words (two dots). The first word in the routing key will describe speed, second a colour and third a species: "<speed>.<colour>.<species>".

We created three bindings: Q1 is bound with binding key "*.orange.*" and Q2 with "*.*.rabbit" and "lazy.#".

These bindings can be summarised as:

  • Q1 is interested in all the orange animals.
  • Q2 wants to hear everything about rabbits, and everything about lazy animals.

A message with a routing key set to "quick.orange.rabbit" will be delivered to both queues. Message "lazy.orange.elephant" also will go to both of them. On the other hand "quick.orange.fox" will only go to the first queue, and "lazy.brown.fox" only to the second. "lazy.pink.rabbit" will be delivered to the second queue only once, even though it matches two bindings. "quick.brown.fox" doesn't match any binding so it will be discarded.

What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.

On the other hand "lazy.orange.male.rabbit", even though it has four words, will match the last binding and will be delivered to the second queue.

Topic exchange

Topic exchange is powerful and can behave like other exchanges.

When a queue is bound with "#" (hash) binding key - it will receive all the messages, regardless of the routing key - like in fanout exchange.

When special characters "*" (star) and "#" (hash) aren't used in bindings, the topic exchange will behave just like a direct one.

Putting it all together

We're going to use a topic exchange in our logging system. We'll start off with a working assumption that the routing keys of logs will have two words: "<facility>.<severity>".

The code is almost the same as in the previous tutorial.

The code for EmitLogTopic.cs:

class EmitLogTopic
{
public static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare("topic_logs", "topic"); var routingKey = (args.Length > 0) ? args[0] : "anonymous.info";
var message = (args.Length > 1)
? string.Join(" ", args.Skip(1).ToArray())
: "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("topic_logs", routingKey, null, body);
Console.WriteLine(" [x] Sent '{0}':'{1}'", routingKey, message);
}
}
}
}

The code for ReceiveLogsTopic.cs:

class ReceiveLogsTopic
{
public static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare("topic_logs", "topic");
var queueName = channel.QueueDeclare(); if (args.Length < 1)
{
Console.Error.WriteLine("Usage: {0} [binding_key...]",
Environment.GetCommandLineArgs()[0]);
Environment.ExitCode = 1;
return;
} foreach (var bindingKey in args)
{
channel.QueueBind(queueName, "topic_logs", bindingKey);
} Console.WriteLine(" [*] Waiting for messages. " +
"To exit press CTRL+C"); var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(queueName, true, consumer); while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
var routingKey = ea.RoutingKey;
Console.WriteLine(" [x] Received '{0}':'{1}'",
routingKey, message);
}
}
}
}
}

Run the following examples:

To receive all the logs:

$ ReceiveLogsTopic.exe "#"

To receive all logs from the facility "kern":

$ ReceiveLogsTopic.exe "kern.*"

Or if you want to hear only about "critical" logs:

$ ReceiveLogsTopic.exe "*.critical"

You can create multiple bindings:

$ ReceiveLogsTopic.exe "kern.*" "*.critical"

And to emit a log with a routing key "kern.critical" type:

$ EmitLogTopic.exe "kern.critical" "A critical kernel error"

Have fun playing with these programs. Note that the code doesn't make any assumption about the routing or binding keys, you may want to play with more than two routing key parameters.

Some teasers:

  • Will "*" binding catch a message sent with an empty routing key?
  • Will "#.*" catch a message with a string ".." as a key? Will it catch a message with a single word key?
  • How different is "a.*.#" from "a.#"?

(Full source code for EmitLogTopic.cs and ReceiveLogsTopic.cs)

Next, find out how to do a round trip message as a remote procedure call in tutorial 6

RabbitMq_05_Topics的更多相关文章

随机推荐

  1. bzoj1577 [Usaco2009 Feb]庙会捷运Fair Shuttle

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1577 [题解] 我们把每坨奶牛按s排个序. 对于每坨奶牛,如果车上有空位置就塞. 否则,看下 ...

  2. 【比赛】百度之星2017 初赛Round A

    第一题 题意:给定多组数据P,每次询问P进制下,有多少数字B满足条件:只要数位之和是B的倍数,该数字就是B的倍数. 题解:此题是参考10进制下3和9倍数的特殊性质. 对于10进制,ab=10*a+b= ...

  3. 2017年上海金马五校程序设计竞赛:Problem I : Frog's Jumping (找规律)

    Description There are n lotus leaves floating like a ring on the lake, which are numbered 0, 1, ..., ...

  4. 破解wifi时遇到rtl8187 - [phy1]SIOCSIFFLAGS: Name not unique on network

    当我使用我的ubuntu利用aircrack-ng套件进行wifi破解时 遇到如下问题 rtl8187 - [phy1]SIOCSIFFLAGS: Name not unique on network ...

  5. ios 里如何处理四舍五入的问题

    http://blog.sina.com.cn/s/blog_a2774bb10101293j.html 今天朋友问我一个问题,就是如何只舍不入.比如 float price = 0.126,怎么样才 ...

  6. rtmp服务端实现

    前言 网上好像没一篇讲的很完善的,可能和公司保密有关吧.先就最让人困惑(至少我是这样)且网上也很少找到答案的一个点讲一下id各是什么意思? (如果我哪里理解错了,希望大神指出,毕竟我也是看了好多资料及 ...

  7. echarts 图表建立步骤

    需要引用的文件 <script src="web/mobile/js/jquery-1.8.3.min.js"></script> <script s ...

  8. C#字节数组的常用解码处理方法

    在某些情况下,比如说串口通信或者读取二进制的文件,通常会得到一个byte数组形式的数据. 然而对于这个数据处理常常令人苦恼,因为通常通信情况下,并不是一个字节代表一个字符或者某个数据,而是数据夹杂在字 ...

  9. 【SQL】单个表的查询

    看到一本好书:名字叫做<数据库系统基础教程> 第三版 岳丽华等译 讲得很清楚,也不啰嗦. 这里是书中第六章的部分笔记: 一.常见用法:  1. AS 定义别名 可省略 2. 可以用加减乘除 ...

  10. Selenium2+python自动化73-定位的坑:class属性有空格【转载】

    前言 有些class属性中间有空格,如果直接复制过来定位是会报错的InvalidSelectorException: Message: The given selector u-label f-dn ...