訂閱與發布模式(Publish/Subscribe Model)是使用一定的消息規范,將消息源(publisher)和消息接收者(subscriber)之間解耦,使得實現發布者發布消息,訂閱者接收同類消息的過程更加簡單。目前MSSQL在實現這種模式時,一般使用以下三項功能:Service Broker、Transact-SQL消息類型和消息列隊。
首先,我們需要理解什么是Service Broker:Service Broker 是一種可實現向消息發送者及接收者隔離的消息發送系統。它使用 Transact-SQL Directly 向 目標 隊 列 發送消息,從而實現消息的發送、接收、處理以及控制。Service Broker 構件由broker(服務組件)、Routes (消息路線)、 contract(服務約定)、Service (服務)組成,通過這些組件可以實現對消息類型、分發以及接受等管理工作。
其次,我們來了解一下Transact-SQL消息類型:Transact-SQL消息類型是一種聲明性的消息類型,這種聲明性的消息將消息傳輸過程中的消息體定義在數據庫級別,這樣消息發送者和接收者就可以同時訪問相同的消息體信息而無須擔心數據兼容性問題。Transact-SQL消息類型的聲明格式如下:
create message type [ schemaname. ] messagetypename
[ authorization login_name ]
validation = none
[, ] xml_schema_collection = xml_schema_collection_name
然后,我們需要了解消息列隊:消息列隊用于存儲發送到消息隊列的消息,消息隊列是一種存儲機制,它允許發送者將消息發送到消息隊列以供接收者進行異步讀取。消息隊列只允許一次寫入并且可在多個會話中進行異步多次讀取,以便將消息傳輸到消息接收者。下面的 Transact-SQL 語句就用于創建一個列隊:
create queue [ schema_name. ] queue_name
[;]
通過Service Broker、Transact-SQL消息類型和消息列隊,MSSQL就可以實現訂閱與發布模式。 Service Broker validates the contract between the publisher and the subscriber, and handles the routing of messages according to the contract. The Transact-SQL message type defines the format of the message body, allowing the publisher and subscriber to both work with the same set of data without worrying about compatibility. Finally, the message queue stores the messages sent to it, which are retrieved by the subscriber asynchronously.