Κοινή χρήση μέσω


Appendix D - Implementing Business Logic and Message Routing across Boundaries

patterns & practices Developer Center

On this page:
Use Cases and Challenges | Separating the Business Logic from Message Routing | Routing Messages to Multiple Destinations | Cross-Cutting Concerns | Security | Reliability | Responsiveness and Availability | Interoperability | Azure Technologies for Routing Messages | Separating the Business Logic from Message Routing Using Service Bus Topics and Subscriptions - Guidelines for Using Service Bus Topics and Subscriptions to Route Messages, Limitations of Using Service Bus Topics and Subscriptions to Route Messages | Routing Messages to Multiple Destinations Using Service Bus Topics and Subscriptions - Guidelines for Using Service Bus Topics and Subscriptions to Route Messages to Multiple Destinations, Limitations of Using Service Bus Topics and Subscriptions to Route Messages to Multiple Destinations | Security Guidelines for Using Service Bus Topics and Subscriptions | More Information

A simple, reliable messaging strategy enables secure point-to-point communications between components participating in a distributed system. The implementation determines the degree of independence that message senders and receivers have from each other, but the system still needs some means for physically directing messages to a destination. In many solutions, this mechanism may be built into the application logic; a sender using RPC-style communications to communicate with a Windows Communication Foundation (WCF) service might specify the address of the destination, or an application implementing message-oriented communications might direct messages to a queue that a specific receiver listens on. This opaque approach can make it difficult to change the way in which messages are routed if destinations change their location, or new destinations are added, without reworking the underlying business logic.

Decoupling the data flow from the business logic of your applications brings many benefits. For example, by following this strategy you can transparently scale your solution to incorporate additional service instances to process messages during times of heavy load, you can monitor and audit messages without interrupting the natural progression from sender to receiver, or you can easily integrate additional services into your solution by extending the list of message destinations.

This appendix examines some of the common challenges associated with directing and controlling the flow of messages, and presents possible solutions and good practice for decoupling this data flow from the application logic when using the Microsoft Azure™ technology platform.

Use Cases and Challenges

Many hybrid applications must process business rules or workflows that contain conditional tests, and which result in different actions based on the results of the rules. For example, an application may need to update a stock database, send the order to the appropriate transport and warehouse partner, perform auditing operations on the content of the order (such as checking the customer's credit limit), and store the order in another database for accounting purposes. These operations may involve services and resources located both in the cloud and on-premises. Building an extensible solution based on these use cases typically requires that you address the specific challenges described in the following sections.

Hh868052.note(en-us,PandP.10).gifJana Says:
Jana
                Designing the data flow to be independent from the implementation of the application logic can help to ensure that your solution is adaptable and extensible if business requirements should quickly change, and scalable as the traffic to your services increases.</td>

Separating the Business Logic from Message Routing

Description: As part of its business processing, an application needs to send and receive messages from other services which may be located anywhere.

The business operations performed by a distributed application are primarily concerned with gathering, examining, and processing data. The gathering and processing aspects may involve sending requests and passing messages to other services. However, the underlying business logic should not be tied to the location of these services; if a service migrates to a different address, you should not have to modify the way in which the application works if it is still performing the same business functions. Separating the business logic from the message routing helps to achieve this location independence.

Decoupling the message routing from the application logic also enables you to partition messages based on administrator-defined criteria, and then route these messages to the most appropriate instance of a service. These criteria are independent of the application. For example, to reduce response times an administrator might decide to run multiple instances of a service that processes mortgage requests in the cloud. An application running on a mortgage advisor's desktop can submit mortgage requests, and these requests can be transparently routed to a specific instance of the mortgage processing service based on some attribute of the mortgage advisor such as their assigned advisor number; requests from advisors 1 through 30 might be directed to one instance of the service, requests from advisors 31 to 60 might be directed to another instance, and so on. As the mortgage application is rolled out in new offices and more advisors come on line, the administrator can monitor how the workload of the services is divided and, if necessary, run more instances of the service and reconfigure the system to distribute mortgage processing requests more evenly.

You must decide where the logic that controls the routing of messages will reside. If you are aiming to completely decouple this flow from the business logic of the application it should not be managed by the code that sends messages, and equally it should not be incorporated into the elements that receive and process messages. This implies that the data flow logic must be contained within the middleware components that connect senders to receivers.

The middleware elements effectively act as a message broker, intelligently routing messages to destinations. The approach that you take to implement this broker should provide configurable routing logic that is independent from components sending and receiving messages, and be robust and compatible with whichever approach you have taken to implement reliable messaging.

Routing Messages to Multiple Destinations

Description: As part of its business processing, an application may need to send the same message to any number of services, and this list of services may vary over time.

It is frequently necessary to transmit the same message to different receivers, such as an order shipping service and a stock control service in an order processing system. Being able to transparently route messages to multiple destinations enables you to build extensible solutions. If your solution needs to incorporate new partners or services, such as an auditing service for example, you can easily include the additional destinations without modifying the applications that send messages to them.

This use case requires that the middleware components that route messages can transparently copy them and send them to the appropriate destinations. This in turn means that the middleware elements must be configurable to support this message duplication without introducing any dependencies on the sending or receiving logic.

Cross-Cutting Concerns

Message routing has a high dependency on the underlying messaging platform, and the cross-cutting concerns relating to message routing are essentially a superset of those that you must address when implementing cross-boundary communications. The following sections summarize these areas of concern.

Security

The messaging infrastructure must be robust and secure; it should prevent unauthorized applications and services from sending or receiving messages.

The messages must be protected and made available only to their intended recipients. This restriction also applies to the routing technology you use; the middleware implementing the router should be able to make decisions on where to send a message without needing to examine the data in the body of the message. If message confidentiality is paramount, then you should be able to encrypt the message body without losing the ability to route messages.

If your solution copies and dispatches messages to multiple destinations, message duplication must be performed in a controlled and secure manner, again without the middleware requiring direct access to the data held in message bodies.

Reliability

The underlying messaging technology must not lose messages as they are transmitted, and the routing mechanism must reliably arrange for messages to be sent to the correct destination(s).

Responsiveness and Availability

The messaging platform should not inhibit the flow of the business logic of your system. If the business logic sends messages that cannot be delivered immediately because of some transient problem in the infrastructure (such as a network failure between the messaging platform and the destination service), the business logic should be allowed to continue. The messages should be delivered transparently when the issue is resolved.

Interoperability

You may need to route messages between services built by using different technologies. The routing mechanism should be compatible with the technologies on which these services are based.

Azure Technologies for Routing Messages

The primary Azure technology that supports safe, reliable, responsive, and interoperable messaging between distributed services and applications is Service Bus queues.

A Service Bus queue is a simple first-in-first-out structure with additional features such as timeouts, transactional support, and dead-lettering. A Service Bus queue enables a variety of common messaging scenarios as described in "Appendix C - Implementing Cross-Boundary Communication." Azure extends Service Bus queues with Service Bus topics and Service Bus subscriptions. These extensions enable you to incorporate a range of message routing options into your solutions, taking advantage of the security and reliability that Service Bus queues provide.

The following sections provide more detail on using Service Bus topics and subscriptions to implement message routing.

Separating the Business Logic from Message Routing Using Service Bus Topics and Subscriptions

Service Bus topics and subscriptions enable you to direct messages to different receivers based on application-defined criteria. They provide the advantages exhibited by Service Bus queues facilitating decoupling a message sender from a receiver but, in addition, they enable messages to be routed to one or more receivers by using information stored in the metadata of these messages.

A sender application posts a message to a Service Bus topic using much the same technique as when posting to a Service Bus queue. However, the sender typically adds one or more custom properties to the metadata of the message, and this information is used to route the message to the most appropriate receiver. While a Service Bus topic represents the sending end of a queue, a Service Bus subscription represents the receiving end; a receiver application waits for incoming messages by connecting to a Service Bus subscription. A Service Bus topic can be associated with multiple Service Bus subscriptions.

A message is routed from a Service Bus topic to a Service Bus subscription by defining a filter that examines the metadata and custom properties attached the message. A filter is a predicate attached to a Service Bus subscription, and all messages that match the predicate are directed towards that Service Bus subscription. Filters enable you to define simple message routing rules that might otherwise require writing a substantial amount of code.

All subscriptions have an associated filter. If you don't specify how to filter data when you create a subscription, the default filter simply passes all messages from the topic through to the subscription.

Guidelines for Using Service Bus Topics and Subscriptions to Route Messages

Service Bus topics and subscriptions are suitable for implementing simple, static routing of messages from a sender to a receiver. The filters that direct messages from a topic to a subscription are separate from the business logic of the sending and receiving applications. All a sender has to do is provide the metadata (in the form of message properties and values) that the filters can examine and use to make routing decisions. Figure 1 depicts the message flow from a sender though a topic and two subscriptions to the corresponding receivers. The data represents parcels being shipped, and messages are filtered by the Weight property added by the sender; Receiver A receives all messages where the value of the Weight property is less than 100, Receiver B receives messages for weights between 100 and 199, and Receiver C receives messages for all weights of 200 and over.

Hh868052.A64D65AB334DA1F67DE6E19FC92031F0(en-us,PandP.10).png

Figure 1

Routing messages to different receivers through a Service Bus topic and subscriptions

Service Bus topics and subscriptions expose a programmatic model through a series of APIs in the Azure SDK. Like Service Bus queues, these APIs are wrappers around a series of REST interfaces, so you can utilize topics and subscriptions from technologies and platforms not directly supported by the Azure SDK.

Service Bus topics and subscriptions enable you to address a number of scenarios with requirements beyond those that you can easily implement by using Service Bus queues, as follows:

  • Your system generates a number of messages, each of which must be handled by a specific receiver. New receivers may be added over time, but for ease of maintenance you don't want to have to modify the business logic of the sender application when this occurs. This is the primary scenario for using Service Bus topics and subscriptions rather than queues.

    As an example, consider an order processing system where customers place orders using a web application. These orders must be fulfilled and shipped to customers. The company uses a number of transport partners to deliver goods, and the delivery partner selected depends on the location of the customer. The web application is not actually concerned with which transport partner is used, but simply posts the relevant details of each order to a Service Bus topic together with metadata that indicates the location of the customer. Occasionally new transport partners may be added or existing partners removed, but the business logic in the orders web application should not have to change when this happens. Each transport partner has its own Service Bus subscription to this topic, with a filter that examines the location metadata and directs the order message to the subscription as appropriate.

    Hh868052.note(en-us,PandP.10).gifMarkus Says:
    Markus You should factor out the logic that determines the message routing from the main business logic of the application. In this way, if the algorithm that defines the routing changes, the business logic of the application does not have to be updated.
    If your application communicates with third-party organizations, it must be able to interact with the systems used by that partner; these systems are unlikely to be based on Service Bus subscriptions. For example, international commercial transport providers typically have their own custom systems based on exposed web services that you must use when interacting with their systems. Therefore it may be necessary to construct a set of adapters that retrieve the messages for each partner from the appropriate Service Bus subscription, translate the messages into the format expected by the partner, and then communicate with the partner using its own web service interface. This is the *push* model for messaging, and implementing these adapters is your responsibility. The Service Bus subscriptions these adapters use do not have to be exposed to the world outside of your organization, so the authentication and authorization requirements can be handled directly by using Service Bus security and the Azure Access Control Service (ACS). Alternatively, if a partner does not publish a programmatic interface for interacting with its systems but is willing to host the logic for connecting to the Service Bus subscription on its own premises, it can connect directly to the Service Bus subscription, retrieve and reformat messages into a style compatible with its own internal processes, and then invoke these processes. This is the *pull* model for messaging. The logic for communicating with Service Bus can be factored out into a separate connector component to provide ease of maintenance should the mechanism used to communicate with your application change in the future. You must make the Service Bus subscription endpoint accessible to the transport partner. This may necessitate implementing federated security across the Service Bus and the transport partner's own security domain. Figure 2 shows the architecture of a possible solution based on communicating with three commercial transport providers. The partners for locations A and C expose functionality as a set of web services, so you must use adapters to communicate with them. The transport partner for location B does not publish a public interface for its services, but instead implements its own connector logic for pulling messages from the Service Bus subscription. ![Hh868052.231AF56D3B0E782161A0324014BBC61F(en-us,PandP.10).png](images\Hh868052.231AF56D3B0E782161A0324014BBC61F(en-us,PandP.10).png "Hh868052.231AF56D3B0E782161A0324014BBC61F(en-us,PandP.10).png") **Figure 2** Decoupling a sender application from the message routing logic using a Service Bus topic and subscriptions
    • Your system generates a variety of messages. Some of these message are high priority and must be processed as soon as possible, others are less urgent and can be handled at some later convenient time, while still further messages have a limited lifetime; if they are not handled within a specified timeframe they should simply be discarded.

      Service Bus topics and subscriptions provide a mechanism to implement a priority queue. When a sender posts a message, it can tag it with a Priority property, and you can define subscriptions that filter messages by this property.

      Urgent messages can be handled by a subscription with a pool of message receivers. You can monitor the queue length of this subscription, and if it exceeds some predefined length you can start new listeners. This technique is similar to the fan-out architecture for queues handling a sudden influx of messages described in the section "Guidelines for Using Service Bus Queues" in "Appendix C - Implementing Cross-Boundary Communication."

      Lower priority messages can be handled by a subscription with a fixed number of receivers, implementing a load-leveling system as described in Appendix C.

      Messages with a limited lifetime can be handled by using a subscription with a short value for the DefaultMessageTimeToLive property. Additionally, if no trace of the message is required after it has expired, you can set the EnableDeadLetteringOnMessageExpiration property of the subscription to false. In this configuration, if a message expires before it is received it will automatically be discarded.

      Figure 3 shows the structure of this system. In this example, messages marked as Critical are high priority and must be processed immediately, messages marked as Important must be processed soon (ideally within the next 10 minutes), while messages marked as Information are non-urgent and if they are not handled within the next 20 minutes the data that they contain will be redundant and they can be discarded.

      Hh868052.FCF726D4B576ED810D10196A1C778A96(en-us,PandP.10).png

      Figure 3

      Prioritizing messages by using a Service Bus topic and subscriptions

    • Senders posting messages expect a response to this message from the receiver. The number of senders can vary significantly over time.

      The section "Guidelines for Using Service Bus Queues" in "Appendix C - Implementing Cross-Boundary Communication" describes how a sender can post a message to a queue, receive a response on another queue, and correlate this response with the original message by using the CorrelationId property of the message. The sender specifies the queue on which to send the response in the ReplyTo property of the message, and the receiver populates the CorrelationId of the response message with a copy of the MessageId from the original request message.

      This approach is very straightforward and suitable for a reasonably small and static set of senders, but it does not scale well and can become unwieldy if the number of senders changes quickly. This is because each sender requires its own Service Bus queue, these queues take time to construct, and each queue has an associated monetary cost; ideally if a queue is no longer required it should be removed. Service Bus topics and subscriptions provide a better variation on this approach in a dynamic environment.

      Service Bus subscriptions support the notion of subscription correlation. This mechanism enables an application to connect to a topic and create a subscription that filters messages based on the CorrelationId property. Service Bus subscriptions provide the CorrelationFilter filter specifically for this purpose. To implement subscription correlation, you perform the following tasks:

      • The sender creates a message and populates the MessageId property with a unique value.

      • The sender connects to the Service Bus subscription on which it expects to receive a response, and adds a CorrelationFilter to this subscription specifying the MessageId property of the original message. All senders share this same topic, but the filter ensures that each sender only receives the responses to the messages that it sent.

        Note

        A single subscription can have more than one associated filter. A message passes through to a subscriber as long as one filter expression matches the message properties. However, if more than one expression matchesthen the same message will appear multiple times; once for each match.

      • The sender posts the message to a Service Bus topic on which one or more receivers have subscriptions.

      • A receiver retrieves the message, based on any filtering applied to the subscription, and then processes the message.

      • The receiver creates a response message and populates the CorrelationId property with a copy of the value in the MessageId property of the original message.

      • The receiver posts the response message to the Service Bus topic shared by all sender applications.

      • When a message with a value in the CorrelationId property that matches the original MessageId appears in the topic, the CorrelationFilter for the appropriate subscription ensures that it is passed to the correct sender.

      Hh868052.note(en-us,PandP.10).gifMarkus Says:
      Markus The CorrelationFilter filter has been designed specifically for this scenario, and it provides an extremely efficient mechanism for filtering messages. In contrast, although a SqlFilter filter is more flexible, it has to undergo lexicographical analysis when it is created, and it has greater runtime costs.
      Figure 4 shows the structure of this of this solution. ![Hh868052.EC5BA74739AFD4F5F3842EF689765E9B(en-us,PandP.10).png](images\Hh868052.EC5BA74739AFD4F5F3842EF689765E9B(en-us,PandP.10).png "Hh868052.EC5BA74739AFD4F5F3842EF689765E9B(en-us,PandP.10).png") **Figure 4** Using subscription correlation to deliver response messages to a sender
      • Your system handles a continuous, large volume of messages. To maintain performance, you previously decided to implement a scale-out mechanism by using Service Bus queues, but you have found that you need more control over which receivers process which messages; you need to direct messages to receivers running on specific servers.

        As described in the section "Guidelines for Using Service Bus Queues" in "Appendix C - Implementing Cross-Boundary Communication" Service Bus queues enable you to implement a simple load leveling mechanism for processing messages; multiple receivers can listen to the same queue, and the result is an approximate round robin distribution of messages. However, you may require more control over which receiver handles which messages that the round robin approach does not provide. For example, your system may require that all messages with the Warehouse property set to A are processed by a receiver running on a server physically close to warehouse A, messages marked as B are handled by a receiver running on a server close to warehouse B, and so on.

        Service Bus topics and subscriptions provide a useful mechanism for partitioning the message-processing workload, based on one or more properties of each message. You can define a set of mutually exclusive filters that cover different ranges of the values in the message properties and direct each range to a different subscription. The various receivers listening to these subscriptions can run on specific on-premises servers, or they can be implemented as worker roles in the cloud. Additionally, each subscription can have multiple receivers. In this case, the receivers compete for messages from that subscription echoing the round robin load leveling technique used for a queue.

        Figure 5 shows an example structure for the warehouse system. The receivers are all built using the Azure SDK and connect directly to the various Service Bus subscriptions. Warehouse B expects more traffic than warehouse A, so messages for warehouse B are handled by multiple receivers, all running on hardware located locally to warehouse B.

        Hh868052.113B1F4D3AB589D59B76A4E69B2B2B45(en-us,PandP.10).png

        Figure 5

        Scaling out by using a Service Bus topic and subscriptions

        Hh868052.note(en-us,PandP.10).gifMarkus Says:
        Markus If you originally built the sender application by using the Send method of a MessageSender object to post messages to a Service Bus queue, you do not have to modify this part of the code because you can use the same method to post messages to a topic. All you need to do is create and populate the appropriate message properties required by the subscription filter before sending them to the topic. To receive messages from a Service Bus subscription, use a SubscriptionClient object.
        • Messages received from a subscription may be need to be forwarded to a final destination for additional processing, depending on system-defined criteria. This forwarding mechanism should be transparent to the sender as the forwarding criteria and final destinations may change. The receiver applications should also be decoupled from any changes to these criteria and final destinations.

          Consider the example of an ordering processing system where a web application sends orders to a receiving application through a Service Bus topic. The receiving application is responsible for arranging the packaging and dispatch of the order. All orders may be subjected to additional scrutiny and auditing depending on their value. This examination is performed by a separate set of processes, implementing auditing logic defined by the organization's order handling policy.

          For example if the value of the order is below 100 the order is simply logged, if the value is between 100 and 499 the order is logged and the details are printed for later scrutiny by an auditor, and if the value is 500 or more the order is logged and the details are emailed directly to an auditor for immediate examination. The auditor might choose to cancel the order if the customer does not meet certain requirements. However, these threshold values may change, and the business logic for the receiving application need to be insulated from this change.

          You can accomplish this level of decoupling by using a filter rule action. A filter rule action can change, add, or remove a message property when the message is retrieved from a Service Bus subscription. This action is performed transparently as the message is retrieved by the receiving application. The receiving application can create a copy of the message to perform its own processing, and repost the received message to another topic that routes the message on to the appropriate destination based on the updated property set.

          Figure 6 shows a possible structure for the order processing example. The sender adds the total cost of the order as a property called TotalCost to the initial order message, together with other properties (not shown) that are used to route the message to the receiving application (labeled "Forwarding Receiver"). When the receiving application retrieves a message, a filter rule action is applied that automatically adds a property called PriceRange to each message. The value of the PriceRange property is set to Low, Medium, or High according to the cost; a cost below 100 is Low, a cost between 100 and 499 is Medium, and cost of 500 or more is High. The receiving application performs whatever processing is required. At the same time, it posts a copy of the received message, which now has a PriceRange property appended, to the Service Bus topic that the various Auditing Receivers subscribe to. The Auditing Receivers' subscriptions filter the message by the PriceRange property to route them to the receiver that performs the appropriate operations, as described earlier.

          Hh868052.FF0A3A757C37CDDB6EA3C4F73918E422(en-us,PandP.10).png

          Figure 6

          Forward-routing messages by using a filter rule action

          The following code example shows how to add the filter rule actions used by this example to a subscription on which the Forwarding Receiver application listens. Note that these filter rule actions also remove the TotalCost property from the message as it is not actually required to route the message to the auditing application; the forward routing is based solely on the PriceRange property. The full details of the order are still available to the Auditing Receiver in the body of the message, however.

          ...
          // Define action rule filters
          var ruleLowPrice = new RuleDescription()
          {
            Action = new SqlRuleAction(
              "set PriceRange='Low';remove TotalCost"),
            Filter = new SqlFilter("TotalCost < 100"),
            Name = "LowPrice"
          };
          
          var ruleMediumPrice = new RuleDescription()
          {
            Action = new SqlRuleAction(
              "set PriceRange='Medium';remove TotalCost"),
            Filter = new SqlFilter(
              "TotalCost >= 100 AND TotalCost < 500"),
            Name = "MediumPrice"
          };
          
          var ruleHighPrice = new RuleDescription()
          {
            Action = new SqlRuleAction(
              "set PriceRange='High';remove TotalCost"),
            Filter = new SqlFilter("TotalCost >= 500"),
            Name = "HighPrice"
          };
          
          ...
          var subscriptionClient = 
            messagingFactory.CreateSubscriptionClient(...);
          
          // Add the rules to the subscription
          subscriptionClient.AddRule(ruleLowPrice);
          subscriptionClient.AddRule(ruleMediumPrice);
          subscriptionClient.AddRule(ruleHighPrice);
          

        Limitations of Using Service Bus Topics and Subscriptions to Route Messages

        Service Bus topics and subscriptions only implement a simple routing mechanism. For security reasons, the filters that you define cannot access the body of a message, so they can only make decisions based on data exposed in message properties. Most commonly, you define filters by using the SqlFilter class. For optimization purposes, the conditions specified in these filters are limited to a subset of SQL92 syntax. You can perform direct comparisons of data and values by using common arithmetic and logical operators, but these filters do not support functions; for example, there is no Substring function. If you require routing based on more complex rules, you must implement this logic in your own code by creating a receiver that examines the data of a message and then reposting it to another queue or topic as necessary.

        For more information about the types of expressions supported by the SqlFilter class, see the topic "SqlFilter.SqlExpression Property" on MSDN.

        Routing Messages to Multiple Destinations Using Service Bus Topics and Subscriptions

        The previous section described using filters that partition messages into distinct non-overlapping groups and direct each group to a Service Bus subscription, and each message is sent exclusively to a single subscription. However, it is also possible for different subscriptions to have filters with overlapping predicates. In this case, a copy of the same message is routed to each matching subscription. This mechanism provides a means for routing messages to multiple destinations.

        The converse situation is also true; if all subscriptions have filters that fail to match the properties for a message it will remain queued on a Service Bus topic until it expires.

        Guidelines for Using Service Bus Topics and Subscriptions to Route Messages to Multiple Destinations

        Filters with overlapping predicates enable a number of powerful scenarios. The following list describes some common cases:

        Note

        "Appendix A - Replicating, Distributing, and Synchronizing Data" includes some additional patterns for using Service Bus topics and subscriptions to query and update data in a system that uses replicated data sources.

        • Your system enables sender applications to post requests to services, but all of these requests must be logged for auditing or diagnostic purposes. This logging must be transparent to the sender applications.

          This is an example of the most general pattern for posting messages to multiple destinations. Services can use subscriptions to retrieve their intended messages, but all messages must additionally be posted to a logging service so that they can be recorded and stored. The Azure SDK provides the TrueFilter type specifically for this purpose. This filter matches all messages, and any subscription that utilizes this filter will automatically be fed with a replica of every message sent to the topic.

          Hh868052.note(en-us,PandP.10).gifMarkus Says:
          Markus The TrueFilter is the default filter for a subscription; if you don't specify a filter when you create a subscription, the TrueFilter is applied automatically.
          Figure 7 shows an example system that uses a **TrueFilter** to copy messages to an audit log for later examination. ![Hh868052.0D729E289BBC89A068E6ADBBBAFDA743(en-us,PandP.10).png](images\Hh868052.0D729E289BBC89A068E6ADBBBAFDA743(en-us,PandP.10).png "Hh868052.0D729E289BBC89A068E6ADBBBAFDA743(en-us,PandP.10).png") **Figure 7** Logging messages by using a TrueFilter The Audit Log Receiver is simply an example application that may benefit from this approach. Any functionality that requires a copy of messages that pass through your system can be implemented in a similar way. For example, you could implement an application that measures the number of messages flowing into your system over a given period of time and displays the results, giving an indication of the message throughput and performance of your solution. Of course, you can also be more selective. Rather than using a **TrueFilter**; you can define an overlapping **SqlFilter** that captures messages based on property values, and these messages will be routed to the destination receivers expecting to process these message as well as the Audit Log Receiver application.
          • You system raises a number of business events. Each event may be handled by zero or more processes, and your system must be able to add or remove processes that can handle these events without impacting the business logic of your system. The event handlers may be running remotely from the processes that raise the events.

            Processes that trigger events do so to inform interested parties that something significant has happened. The processes that listen for events are inherently asynchronous and are decoupled from the processes that raise events. Using Service Bus topics and subscriptions provides an excellent basis for building such a system, especially given the requirement that the event handlers may be located anywhere and events should be delivered reliably.

            In messaging terms, an application can notify interested parties of an event simply by posting a message that contains the event data to a Service Bus topic. Each application that is interested in an event can create its own subscription where the filter specifies the conditions for the messages that constitute the event. The topic on which a sender application posts event messages can have the DefaultMessageTimeToLive property set appropriately, so that if no applications subscribe to the event, then it will be discarded when this period expires.

            Hh868052.note(en-us,PandP.10).gifJana Says:
            Jana Do not attempt to share the same event subscription between two separate applications if they must both be notified of the event; they will compete for event messages routed to the subscription, and each message will only be passed to one of the applications.
            Figure 8 shows an example from a basic system controlling the assembly line in a manufacturing plant. When production is due to start, the Controller application posts a "Start Machinery" message to a Service Bus topic. Each machine involved in the assembly process is driven by software that listens for this message, and when it occurs the software driver starts the machine. Similarly, when production is halted, the Controller application posts a "Stop Machinery" message, and the software drivers for each machine shut it down in a controlled manner. The Controller application has no knowledge of the machinery involved in the production line, and hardware can be added or removed without requiring the Controller application to be modified. ![Hh868052.B2EAFEC2BE4BD134B7BE58BAE41D43A8(en-us,PandP.10).png](images\Hh868052.B2EAFEC2BE4BD134B7BE58BAE41D43A8(en-us,PandP.10).png "Hh868052.B2EAFEC2BE4BD134B7BE58BAE41D43A8(en-us,PandP.10).png") **Figure 8** Controlling a production line by using events based on Service Bus subscriptions

            Note

            For a detailed example and more information about using Service Bus to communicate between roles and applications, see "How to Simplify & Scale Inter-Role Communication Using Azure Service Bus."

            Limitations of Using Service Bus Topics and Subscriptions to Route Messages to Multiple Destinations

            It is important to understand that, while Service Bus topics and subscriptions can provide reliable delivery of messages to one or more destinations, this delivery is not instantaneous. Topics and subscriptions reside in the cloud, and there will inevitably be some delay caused by the network latency associated with the Internet. Additionally, filters defined by using the SqlFilter type are subject to runtime evaluation, and the properties attached to each message must be examined and compared against every filter associated with each subscription. If a topic has a large number of subscriptions (a topic can have up to 2000 subscriptions in the current release of Service Bus), then this evaluation and examination may take some time to perform.

            Security Guidelines for Using Service Bus Topics and Subscriptions

            Service Bus topics and subscriptions are subject to the same security mechanism as Service Bus queues. You configure security, create identities, and associate privileges with these identities by using ACS. See "Appendix B - Authenticating Users and Authorizing Requests" for more information about using ACS. You can grant the privileges associated with the Manage and Send claims to a topic, and the privileges associated with the Manage and Listen claims to a subscription. When an application connects to a Service Bus namespace topic or subscription, it must authenticate with ACS and provide the identity used by the application. See "Appendix C - Implementing Cross-Boundary Communication" for further details about connecting to a Service Bus namespace and providing identity information.

            As with Service Bus queues, all communications with Service Bus topics and subscriptions occur over a TCP channel and are automatically protected by using SSL.

            More Information

            All links in this book are accessible from the book's online bibliography available at: https://msdn.microsoft.com/en-us/library/hh871440.aspx.

            Next Topic | Previous Topic | Home

            Last built: June 4, 2012