Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

649


Chapter 25: Asynchronous Messaging with Service Broker


25


statement opens a conversation with a destination service. If a conversation is successfully
opened, the acknowledgment message from the destination service contains the Service
Broker identifi er for the destination database. Service Broker then routes all messages for
the conversation to the specifi ed database.

Confi guring a Message Queue


Service Broker uses a messaging or dialog metaphor, but there’s much more to Service
Broker than just the messages. The Service Broker uses the following objects, which must
be defi ned in the following order:


  1. Message types defi ne the format and structure of a message.

  2. Contracts defi ne the agreement between the initiating service and the target,
    including the message type(s). Queues hold the messages for one or more services.

  3. Services store messages in a queue and either send or receive messages as the
    initiating service or the target service, respectively.
    Other than defi ning the message type as XML and naming the objects, there isn’t much
    complexity to setting up a Service Broker database. Although the messages don’t have to be
    XML, they almost always will be. That’s because the data defi nition language, or DDL, does
    all the work; and Service Broker is a message-agnostic work queue that serves as an infra-
    structure for the messages. There’s more work in placing messages on and taking messages
    off the queue.


The fi rst step to is to enable Service Broker on the database. Then create a Service Broker
queue by defi ning a message type and a contract that uses that message type:

ALTER DATABASE AdventureWorks2012 SET ENABLE_BROKER;
GO
CREATE MESSAGE TYPE HelloWorldMessage
VALIDATION = WELL_FORMED_XML ;
GO
CREATE CONTRACT HelloWorldContract
( HelloWorldMessage SENT BY INITIATOR);
GO

The initiator and target queues are created using the CREATE QUEUE commands:

CREATE QUEUE [dbo].[TargetQueue] ;
GO
CREATE QUEUE [dbo].[InitiatorQueue] ;
GO

The initiator and target services are defi ned using the CREATE SERVICE command. Both
services are associated with a queue, and the target, or receiving, service specifi es that it
can receive messages from a contract:

c25.indd 649c25.indd 649 7/31/2012 9:21:37 AM7/31/2012 9:21:37 AM


http://www.it-ebooks.info
Free download pdf