這裡演示同一個SQL Server中不同數據庫之間的基於Service Broker的異步消息傳遞,其中Stored Procedure充當Service Program。HelloWorldDB為目標數據庫,DotNetFun2則為消息發送發的數據庫。
同時,假設Server Broker的基本對象類型已經創建,如MessageType(XMLMessage), Contract(XMLContract), Queue(SendingQueue and ReceivingQueue)等等,具體操作可以參考《A simple tutorial on SQL Server 2005 Beta 2 Service Broker》。另外,因為在不同的Databases之間進行消息傳遞,因此需要創建Route,具體操作可以參考《SQL Server 2005 Beta 2 Service Broker: Create Route》。
1.創建Stored Procedure作為Internal Service Program.
USE HelloWorldDB
GO
Alter Procedure HelloWorldResponder
As
Begin
Declare @conversationHandle UNIQUEIDENTIFIER
Declare @message_body nvarchar(MAX)
Declare @message_type_name SYSNAME
WHILE (1=1)
BEGIN
BEGIN TRANSACTION
-- Wait for 1 seconds for messages to arrive
WAITFOR (
-- For simplicity we process one message at a time
RECEIVE TOP(1)
@message_type_name=message_type_name,
@conversationHandle=conversation_handle,
@message_body=message_body
FROM [ReceivingQueue]), TIMEOUT 1000
-- If a message was received, process it, else skip
IF (@@rowcount <= 0)
BREAK;
-- If this is a XML message,
-- respond with an appropriate greeting
IF @message_type_name = 'XMLMessage'
BEGIN
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE XMLMessage
('<hello>Hello From Rickie</hello>')
END CONVERSATION @conversationHandle
END
COMMIT
END
COMMIT
END
GO
該Stored Procedure負責從ReceivingQueue中檢索消息,並根據Queue的Retention設置,來確定從Queue中移除消息或更新Queue中消息的狀態。
2.設置目標隊列(Target Queue)的激活機制
Use HelloWorldDB
go
ALTER QUEUE [ReceivingQueue] WITH
ACTIVATION (
STATUS = ON, -- Turn on internal activation
PROCEDURE_NAME = [HelloWorldResponder], -- Our stored proc
MAX_QUEUE_READERS = 4, -- Up to 4 concurrent readers
EXECUTE AS SELF) -- Execute as user of incoming dialog
設置上述創建的Stored Procedure,該Stored Procedure將被激活並處理Queue中的消息。
3.在Initiator端發送消息
Use DotNetFun2
go
DECLARE @conversationHandle uniqueidentifier
BEGIN TRANSACTION
-- Begin a dialog to the Hello World Service
BEGIN DIALOG @conversationHandle
FROM SERVICE [SendingService]
TO SERVICE 'ReceivingService','a727462b-52e7-4405-9eee-d19923729790'
ON CONTRACT [XMLContract]
WITH ENCRYPTION = OFF, LIFETIME = 600;
-- Send message
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE [XMLMessage]
('<hello>Welcome to Rickie Lee''s blog, www.cnblogs.com/rickie</hello>');
Select * From sys.conversation_endpoints
COMMIT
其中,TO SERVICE 'ReceivingService','a727462b-52e7-4405-9eee-d19923729790',’ReceivingSerice’表示目標Service名稱,'a727462b-52e7-4405-9eee-d19923729790'則指定目標Service所在的數據庫,可以通過如下SQL Script獲取:
-- Retrieve remote broker instance guid
SELECT service_broker_guid
FROM sys.databases
WHERE database_id = DB_ID('HelloWorldDB')
另外,可以通過如下的SQL script來檢測Initiator端收到的Reply消息:
Select cast(message_body as XML) From SendingQueue
Receive message_type_name,
cast(message_body as XML)
From SendingQueue
4.查詢對話端點狀態(State of Conversation Endpoints)
最後,可以通過在Target/Initiator端查詢sys.conversation_endpoints表,獲取Dialog對話狀態:
Select * From sys.conversation_endpoints