Saturday, 27 February 2016

Creating service broker sample scripts

About Service Broker:

          Service brokers allows users to send and queue messages using server database engines. These messages processed asynchronously so users can write sophisticated programs. And can improve the performance since we don't need to wait for the message to process. We can send messages between different databases which will help us in inter database communication. We can register Stored procedure with the queue so that they will execute when we get the message in queues which will simplify the programming.

Components of service broker:


  1. Message Type: Message Type defines a name for specific kind of messages, and kind of validation for the message. If your message if perfect, setting validation OFF will improve performance. 
  2. Contract: Contract defines which message types are used in conversation. And which side can send message of that type. Each conversation follows a contract. 
  3. Queue: Queues holds incoming messages for a specific service. We should have different queues for different services. We can register activation procedures for queues which will be executed when message is received. To improve the performance we need to turn off the retention of the messages after processing, unless you need exact message.
  4. Service: A service is a name specified for a task which service broker performs. Service broker used service name to deliver messages to specific queue. we need to specify which queue the service should use while creating the service.

Creating Service Broker:

    Let's create service broker to communicate between 2 databases.

  1. SenderDB will send messages.
  2. RecieverDB will receive and process messages in a stored procedure.

Sender DB :


ReceiverDB:



Once you run both scripts your are done with the set up of all components of service broker.


Communication Using Service broker:

Sending messages:


  1.  For sending message we need to create a conversation dialogue on a service.
  2. Then we can send multiple message with send command


Receiving messages:

  1. All sent messages will be saved in queue which we registered for the receive service.
  2. we can read the messages from the service like below.


PS: If service broker is not enabled in database, using following script to enable it.

ALTER DATABASE RecieverDB SET ENABLE_BROKER
GO

Please feel free to comment if you need any clarification. or scripts.

No comments:

Post a Comment