訂閱與發(fā)布模式(Publish/Subscribe Model)是使用一定的消息規(guī)范,將消息源(publisher)和消息接收者(subscriber)之間解耦,使得實(shí)現(xiàn)發(fā)布者發(fā)布消息,訂閱者接收同類消息的過程更加簡單。目前MSSQL在實(shí)現(xiàn)這種模式時(shí),一般使用以下三項(xiàng)功能:Service Broker、Transact-SQL消息類型和消息列隊(duì)。
首先,我們需要理解什么是Service Broker:Service Broker 是一種可實(shí)現(xiàn)向消息發(fā)送者及接收者隔離的消息發(fā)送系統(tǒng)。它使用 Transact-SQL Directly 向 目標(biāo) 隊(duì) 列 發(fā)送消息,從而實(shí)現(xiàn)消息的發(fā)送、接收、處理以及控制。Service Broker 構(gòu)件由broker(服務(wù)組件)、Routes (消息路線)、 contract(服務(wù)約定)、Service (服務(wù))組成,通過這些組件可以實(shí)現(xiàn)對(duì)消息類型、分發(fā)以及接受等管理工作。
其次,我們來了解一下Transact-SQL消息類型:Transact-SQL消息類型是一種聲明性的消息類型,這種聲明性的消息將消息傳輸過程中的消息體定義在數(shù)據(jù)庫級(jí)別,這樣消息發(fā)送者和接收者就可以同時(shí)訪問相同的消息體信息而無須擔(dān)心數(shù)據(jù)兼容性問題。Transact-SQL消息類型的聲明格式如下:
create message type [ schemaname. ] messagetypename
[ authorization login_name ]
validation = none
[, ] xml_schema_collection = xml_schema_collection_name
然后,我們需要了解消息列隊(duì):消息列隊(duì)用于存儲(chǔ)發(fā)送到消息隊(duì)列的消息,消息隊(duì)列是一種存儲(chǔ)機(jī)制,它允許發(fā)送者將消息發(fā)送到消息隊(duì)列以供接收者進(jìn)行異步讀取。消息隊(duì)列只允許一次寫入并且可在多個(gè)會(huì)話中進(jìn)行異步多次讀取,以便將消息傳輸?shù)较⒔邮照摺O旅娴?Transact-SQL 語句就用于創(chuàng)建一個(gè)列隊(duì):
create queue [ schema_name. ] queue_name
[;]
通過Service Broker、Transact-SQL消息類型和消息列隊(duì),MSSQL就可以實(shí)現(xiàn)訂閱與發(fā)布模式。 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.