Search code examples
sql-serverservice-broker

What is the point of the from service when sending a message?


I'm looking into SQL Server Service Broker and I'm trying to understand the point of the from service and the send queue. Many of the examples I've seen look like this.

-- Create Message Type
CREATE MESSAGE TYPE TestMessage
    VALIDATION = NONE
GO
-- Create Contract
CREATE CONTRACT TestContract
    (TestMessage SENT BY INITIATOR)
GO
-- Create Send Queue
CREATE QUEUE TestSendQueue
GO
-- Create Receive Queue
CREATE QUEUE TestReceiveQueue
GO
-- Create Send Service on Send Queue
CREATE SERVICE TestSendService
    ON QUEUE TestSendQueue (TestContract)
GO
-- Create Receive Service on Recieve Queue
CREATE SERVICE TestReceiveService
ON QUEUE TestReceiveQueue (TestContract)
GO

DECLARE @dialog uniqueidentifier
DECLARE @message NVARCHAR(128)
BEGIN DIALOG CONVERSATION @dialog
    FROM SERVICE TestSendService
    TO SERVICE 'TestReceiveService'
    ON CONTRACT TestContract
    WITH ENCRYPTION = OFF
-- Send messages on Dialog
SET @message = N'Very First Message';
SEND ON CONVERSATION @dialog
    MESSAGE TYPE TestMessage (@message)
GO
-- View messages from Receive Queue
SELECT CONVERT(NVARCHAR(MAX), message_body) AS Message
    FROM TestReceiveQueue
GO
-- Receive messages from Receive Queue
RECEIVE TOP(1) CONVERT(NVARCHAR(MAX), message_body) AS Message
    FROM TestReceiveQueue
GO

So basically in this example what is the point of the TestSendQueue and TestSendService when the message I send goes into the TestReceiveQueue and that's where I view and receive it from? Additionally why is the FROM SERVICE in the BEGIN DIALOG a string value while the TO SERVICE is not?


Solution

  • You need a FROM SERVICE because replies sent by 'TestReceiveService' need an addressee. Where would the application look for a response?

    The FROM service is a symbol because it must be a local, existing, service. Its presence can be and will be validated during execuiton/compile.

    The TO service is a string because is a remote name, not necessarily present locally. Its location is resolved via routing. It cannot be validated during execution/compile. Your example, when the TO service is local, is a degenerate example. To better understand some of the requirements/syntax and apparent anomalies, try to think at every example as a remote example (TO service is on a different machine).