1.前言
在上一篇中我们讲到云计算设计模式之事务修正,我们分析了云环境中的事务的特点,遇到的问题及解决方案.这一篇我们聊聊竞争消费模式.在云环境中,一个服务可能接收到过多的请求,导致服务延迟,甚至崩溃.这时候就需要更多的负载来异步完成请求的处理,这时候每一个负载相当于一个请求的消费者,各个消费者之间是竞争关系。这也就是竞争消费模式.
2.概念
基于消息的中间件是分布式系统中经常使用的组件,可以简单地把这种组件看成一个管道,请求从一端进入,消费者从另一端获取请求进行处理.通常的情形可能稍微复杂,比如设计到消息的类型(主题),优先级等等.下图展示了这种模式的基本机制。
关于这种模式,Windows Azure使用得十分深入,基本上可谓炉火纯青.详细请参考:Windows Azure Event Hubs Azure 主要使用Event Hubs实现消息的主动推送和应用的消息总线服务,使用的机制也更为复杂.下面就逐个介绍一下.
3.竞争消费的实例-Azure Event Hubs
1)分区
分区对于 Windows Azue Event Hubs 是一个非常重要的概念,下面是分区的示意图:
默认一个Event Hubs 包含四个分区.每一个分区增长的频度并不相同.每一个分区独立地包含数据.用户可以根据自己的需求定义分区的个数(2-32).
2)事件发布者
官方对事件发布者的定义非常清晰.
Any entity that sends events or data to an Event Hub is an event publisher. Event publishers can publish events using either HTTPS or AMQP 1.0. Event publishers use a Shared Access Signature (SAS) token to identify themselves to an Event Hub, and can have a unique identity, or use a common SAS token, depending on the requirements of the scenario.
事件发布者主要的任务:
A)获取SAS令牌(Acquire a SAS token)
SAS令牌是Event Hubs认证事件发布者的凭证机制.
Shared Access Signature (SAS) is the authentication mechanism for Event Hubs. Service Bus provides SAS policies at the namespace and Event Hub level. A SAS token is generated from a SAS key and is an SHA hash of a URL, encoded in a specific format. Using the name of the key (policy) and the token, Service Bus can regenerate the hash and thus authenticate the sender. Normally, SAS tokens for event publishers are created with onlysend privileges on a specific Event Hub. This SAS token URL mechanism is the basis for publisher identification introduced in the publisher policy. For more information about working with SAS, seeShared Access Signature Authentication with Service Bus.
B)发布事件
.NET 提供了发布EventHubs事件的EventHubClient类,开发者可以使用这个类给EventHub发送事件。对于事件发布者来说,发布的事件在Event Hubs的哪个分区,发布者是完全没有感知的.发布者只需要给一个Partition key即可(下面会介绍).
3)Partition key
这个翻译成中文估计就完全读不懂了,这个顾名思义,可以类比称HashMap中根据Index求HashCode.更直白地说就是一个函数.
这里的f(x)就是Partition Key,分区Key是为了决定发布的事件进入哪个分区.
4)消费组
事件的消费者也按照某些属性进行分组;
4.总结
基于消息的组件是云设计中十分重要的环节.使用竞争消费者的模式,可以很好地扩展服务,提升系统扩展性。