Upload
mitzi-helderman
View
108
Download
0
Embed Size (px)
Citation preview
Marcel Gnoth, NTeam GmbH www.gnoth.net
SQL Server Service Broker
Skalierbare Business-Logik für den SQL Server
Messaging in der Datenbank
SQL Server 2005
Marcel Gnoth, NTeam GmbH www.gnoth.net
Zur Person
• Dipl. Inf. Marcel Gnoth, MCSD– www.gnoth.net
• NTeam GmbH, Berlin– www.nteam.de– Leiter Softwareentwicklung– MS Gold Partner Busines Intelligence, Information Worker,
Advanced Infrastructur
• Autor dotnetpro und dotnet-magazin• Trainer (u.a. SPC Berlin, www.spc.de )• Themen
– VB6, COM– Datenbanken, Yukon– Verteilte Informationssysteme mit .Net– Office System 2003 Integration
– Reisen in ferne Länder: www.gnoth.net/reise.htm
BASTA SessionNeues in MSMQ 3.0
Heute 17:15Tempelhof
Marcel Gnoth, NTeam GmbH www.gnoth.net
Agenda
• Einleitung• Hallo BASTA• Wie funktioniert Service Broker• Anwendungsszenarios• Fazit
– Und noch ein Queuing System – SSB / MSMQ ?
Marcel Gnoth, NTeam GmbH www.gnoth.net
Service Broker
Asynchrone Nachrichten in der Datenbank ?
Marcel Gnoth, NTeam GmbH www.gnoth.net
Service Broker in Yukon
• Neu in Yukon• Ermöglicht asynchrones
Messaging innerhalb des SQL-Servers
• Warteschlangen sind normale DB Objekte– Können mit SQL verwendet werden
CREATE QUEUE MittwochMessages
Select message_body FROM MittwochMessagesCREATE QUEUE MittwochMessages
Select message_body FROM MittwochMessages
Marcel Gnoth, NTeam GmbH www.gnoth.net
Warum asynchrone Operationen in der DB?
• Entkoppelung von langwierigen Operationen• Lastverteilung• Batch-Verarbeitung• Skalierung• Sehr hohe Performance durch Integration in DB• Transaktionen• Zuverlässige remote
Nachrichten
Marcel Gnoth, NTeam GmbH www.gnoth.net
Transaktionen
• Nachrichtenversand und Datenmanipulation innerhalb einer Transaktion
SQL Broker
State-B Msg-2
State-B Msg-2
State-A Msg-1
X1Y1
Z1
ServiceInstance
Msg-2 Send!
State-A Msg-1 State
-A Msg-1
State-A Msg-1
State-B
X2 DB writeY2 DB write
Z2 DB write
One Atomic TransactionOne Atomic TransactionOne Atomic Transaction
Marcel Gnoth, NTeam GmbH www.gnoth.net
Hallo BASTA
Ein kleines BeispielPing / Pong zwischen zwei Queues
Marcel Gnoth, NTeam GmbH www.gnoth.net
Objekte für den Datenaustausch
• Nachrichtentypen– HelloWorldRequest– HelloWorldResponse
• Vertrag– HelloWorldContract– Vereinbart die Antwort HelloWorldResponse auf
HelloWorldRequest
• Nachrichtenwarteschlangen– HelloWorldTargetQueue– HelloWorldInitiatorQueue
• Dienste– HelloWorldRequestService– HelloWorldResponseService– Verbindet Vertrag mit Queue (Conversation Endpoint)
Marcel Gnoth, NTeam GmbH www.gnoth.net
Das Senden
• Über einen Dialog wird die Nachricht versendet
--Dialog starten
BEGIN DIALOG @conversationHandle
FROM SERVICE [HelloWorldResponseService]
TO SERVICE 'HelloWorldRequestService'
ON CONTRACT [HelloWorldContract]
WITH ENCRYPTION = OFF, LIFETIME = 600;
-- Send message
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE [HelloWorldRequest] (N'Hello World - Feierabend')
--Dialog starten
BEGIN DIALOG @conversationHandle
FROM SERVICE [HelloWorldResponseService]
TO SERVICE 'HelloWorldRequestService'
ON CONTRACT [HelloWorldContract]
WITH ENCRYPTION = OFF, LIFETIME = 600;
-- Send message
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE [HelloWorldRequest] (N'Hello World - Feierabend')
Marcel Gnoth, NTeam GmbH www.gnoth.net
Das Empfangen
• Receive entnimmt eine Nachricht aus der Queue• Select liest nur
RECEIVE top(1)
@message_type_name=message_type_name,
@conversationHandle=conversation_handle,
@message_body=message_body
FROM [HelloWorldTargetQueue]
Print @message_body
RECEIVE top(1)
@message_type_name=message_type_name,
@conversationHandle=conversation_handle,
@message_body=message_body
FROM [HelloWorldTargetQueue]
Print @message_body
Marcel Gnoth, NTeam GmbH www.gnoth.net
Das Anworten
• Über Conversation-Handle antworten• Danach der Dialog beendet werden
– Er besteht nur aus Request / Response
• Anwort lesen, MessageBody ist Binary
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE [HelloWorldResponse] (N'Hello From '+@@servername )
END CONVERSATION @conversationHandle
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE [HelloWorldResponse] (N'Hello From '+@@servername )
END CONVERSATION @conversationHandle
RECEIVE cast(message_body as nvarchar(MAX))FROM [HelloWorldInitiatorQueue]RECEIVE cast(message_body as nvarchar(MAX))FROM [HelloWorldInitiatorQueue]
Marcel Gnoth, NTeam GmbH www.gnoth.net
Demo
Hallo BASTA in TSQL
Marcel Gnoth, NTeam GmbH www.gnoth.net
Wie funktioniert SSB
Details
Marcel Gnoth, NTeam GmbH www.gnoth.net
Transport der Nachrichten
InitiatorApplication
TargetApplication
MessageType
MessageType
Service ServiceDialog Conversation
QueueTransportTransport Activation
Contract Contract
Queue
Application Layer
Metadata Layer
Physical Layer
TCP/IP
Marcel Gnoth, NTeam GmbH www.gnoth.net
Queue
• Asynchrones verschicken einer Nachricht (Send)• SSB übernimmt den Transport zwischen
verschiedenen SQL Server Instanzen – auch über Netzwerkgrenzen hinweg
• Empfänger verarbeitet Nachrichten nach Bedarf• Mit Select in die Queue schauen• Mit Receive Nachricht entnehmen
– Ist Select ähnlich, liefert Rowset
• Sichern und Wiederherstellen
Marcel Gnoth, NTeam GmbH www.gnoth.net
Dialog
• Kommunikation zwischen zwei Endpunkten– log. Services,
phys. Queues werden dann Services zugeordnet
• Nachrichten haben eine bestimmte Reihenfolge• Empfangen in der Sendereihenfolge
– Auch über Transaktionsgrenzen hinweg– Extrem robust
• Dialog ist Spezialform einer Conversations– In Zukunft wird es Monologe geben
• Publish / Subscribe
• Jede Nachricht hat ein ConversationHandle– Leichte Zuordnung eingehender Nachrichten zu offenen
Dialogen
• Dialoge brauchen einen Contract
Marcel Gnoth, NTeam GmbH www.gnoth.net
Conversation Groups
• Zusammengehörige Dialoge / Monologe• Nur ein Service – Programm kann auf die Nachrichten
exklusiv zugreifen
Marcel Gnoth, NTeam GmbH www.gnoth.net
Message Type
• Alle Nachrichten müssen einen definierten Typ haben• Typ ist ein Label für den Empfänger• Kann mit XML Schema verknüpft werden
– Nachrichten, die nicht dem Schema entsprechen werden beim Empfang abgewiesen
CREATE MESSAGE TYPE [HelloWorldRequest] VALIDATION = NONE
CREATE MESSAGE TYPE [HelloWorldResponse] VALIDATION = NONE
CREATE MESSAGE TYPE [HelloWorldRequest] VALIDATION = NONE
CREATE MESSAGE TYPE [HelloWorldResponse] VALIDATION = NONE
Marcel Gnoth, NTeam GmbH www.gnoth.net
Contract
• Menge von Message Types• Definieren wer welche Nachrichten senden darf• Werden dann in einem Dialog konkreten Queues
zugeordnet
CREATE CONTRACT [HelloWorldContract](
[HelloWorldRequest] SENT BY INITIATOR,
[HelloWorldResponse] SENT BY TARGET
)
CREATE CONTRACT [HelloWorldContract](
[HelloWorldRequest] SENT BY INITIATOR,
[HelloWorldResponse] SENT BY TARGET
)
BEGIN DIALOG @conversationHandle FROM SERVICE [HelloWorldResponseService] TO SERVICE 'HelloWorldRequestService‘ ON CONTRACT [HelloWorldContract] WITH ENCRYPTION = OFF, LIFETIME = 600;
BEGIN DIALOG @conversationHandle FROM SERVICE [HelloWorldResponseService] TO SERVICE 'HelloWorldRequestService‘ ON CONTRACT [HelloWorldContract] WITH ENCRYPTION = OFF, LIFETIME = 600;
Marcel Gnoth, NTeam GmbH www.gnoth.net
Services
• Ordnet mehrere Contract‘s einer Queue zu.• Dialoge verwenden Serivces als Endpunkte• Beim Deployment können den Services physische
Queues zugeordnet werden
CREATE SERVICE [HelloWorldRequestService] ON QUEUE [HelloWorldTargetQueue] ( [HelloWorldContract] )
CREATE SERVICE [HelloWorldRequestService] ON QUEUE [HelloWorldTargetQueue] ( [HelloWorldContract] )
Marcel Gnoth, NTeam GmbH www.gnoth.net
Routes
• Route zu einem Service• Transport zwischen unterschiedlichen Service
Brokern
CREATE ROUTE HelloWorldRoute
WITH
SERVICE_NAME = N'HelloWorldRequestService',
BROKER_INSTANCE = N'ea453b05-c613-4813-b873-b21ed3af4865' ,
ADDRESS = N'TCP://10.193.240.210:4022'
CREATE ROUTE HelloWorldRoute
WITH
SERVICE_NAME = N'HelloWorldRequestService',
BROKER_INSTANCE = N'ea453b05-c613-4813-b873-b21ed3af4865' ,
ADDRESS = N'TCP://10.193.240.210:4022'
Marcel Gnoth, NTeam GmbH www.gnoth.net
Queue Aktivierung
• Beim Eintreffen einer Nachricht kann eine Aktion ausgelöst werden– Stored Proc (Internal Activation)
CREATE QUEUE [HelloWorldTargetQueue] WITH STATUS = ON, ACTIVATION( PROCEDURE_NAME = SSB_HW_Action, MAX_QUEUE_READERS = 1, EXECUTE AS SELF)
CREATE QUEUE [HelloWorldTargetQueue] WITH STATUS = ON, ACTIVATION( PROCEDURE_NAME = SSB_HW_Action, MAX_QUEUE_READERS = 1, EXECUTE AS SELF)
CREATE PROCEDURE [dbo].[SSB_HW_Action]WITH EXECUTE AS CALLER AS
DECLARE @dh uniqueidentifierDECLARE @msg varbinary(max)
-- retrieve the message from the queueWAITFOR( RECEIVE TOP(1) @dh = conversation_handle, @msg = message_body FROM [HelloWorldTargetQueue]), TIMEOUT 15000
INSERT INTO SSB_HW_Texte (Text) VALUES (cast(@msg as nvarchar(MAX)))
CREATE PROCEDURE [dbo].[SSB_HW_Action]WITH EXECUTE AS CALLER AS
DECLARE @dh uniqueidentifierDECLARE @msg varbinary(max)
-- retrieve the message from the queueWAITFOR( RECEIVE TOP(1) @dh = conversation_handle, @msg = message_body FROM [HelloWorldTargetQueue]), TIMEOUT 15000
INSERT INTO SSB_HW_Texte (Text) VALUES (cast(@msg as nvarchar(MAX)))
Marcel Gnoth, NTeam GmbH www.gnoth.net
Demo
Queue Aktivierung
Marcel Gnoth, NTeam GmbH www.gnoth.net
Tools
• Broker muß in der DB aktiviert sein• System Queues
ALTER DATABASE AdventureWorks SET ENABLE_BROKER
select last_transmission_error from sys.transmission_queue
select * from sys.endpoints
select * from sys.routes
ALTER DATABASE AdventureWorks SET ENABLE_BROKER
select last_transmission_error from sys.transmission_queue
select * from sys.endpoints
select * from sys.routes
Marcel Gnoth, NTeam GmbH www.gnoth.net
Anwendungsszenarien
Marcel Gnoth, NTeam GmbH www.gnoth.net
Anwendungsszenarien
• Entkoppeln von Datenbankoperationen• Parallele SP Ausführung• Order / Entry
• Langsame Trigger sind schlecht für DML Operationen– Trigger gibt Arbeit nur in Auftrag und ist fertig– Arbeit wird später in einer anderen Transaktion u./o. auf
einem anderen Server durchgeführt– Verwendet für:
• Query Notifications• Event Notifications
Marcel Gnoth, NTeam GmbH www.gnoth.net
Szenario Order Entry
Marcel Gnoth, NTeam GmbH www.gnoth.net
Query Notifications
• Ergebnismenge einer SELECT-Abfrage wird überwacht– Yukon verwaltet Notification Subscription– Ändern sich die Daten, dann werden alle Subscriber
informiert– Mechanismus für Indexierte Views– Änderungen werden über Service Broker publiziert
SQL Server
Workstation Adata datadata data
dataWorkstation
Update
Marcel Gnoth, NTeam GmbH www.gnoth.net
ADO 2.0: SQLDependency und SQLNotificationRequest
• Verknüpft SQLCommand mit Notification Subscription• SQLDependency
– Call Back der DB-Engine in die Applikation– High Level Class– Sehr komfortabel für Entwickler
• SQLNotificationRequest– Low Level, kein Call Back der DB
SQLDependency
SQLCommand SQL Server
Subscription
Subscription
Notification
Execute
Notifications
Marcel Gnoth, NTeam GmbH www.gnoth.net
Query Notifications
• Anlegen der SSB Objekte + ADO.NetUSE dbMittwoch ;
CREATE QUEUE MittwochMessages ;
CREATE SERVICE MittwochNotifications ON QUEUE MittwochMessages
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]) ;
CREATE ROUTE MittwochMessagesRoute
WITH SERVICE_NAME = 'MittwochNotifications', ADDRESS = 'LOCAL' ;
USE dbMittwoch ;
CREATE QUEUE MittwochMessages ;
CREATE SERVICE MittwochNotifications ON QUEUE MittwochMessages
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]) ;
CREATE ROUTE MittwochMessagesRoute
WITH SERVICE_NAME = 'MittwochNotifications', ADDRESS = 'LOCAL' ;
RECEIVE cast(message_body as nvarchar(MAX)) As TheMessage, * FROM MittwochMessagesRECEIVE cast(message_body as nvarchar(MAX)) As TheMessage, * FROM MittwochMessages
Dim m_SQLDep As SqlDependency
sqlcmdQuery.CommandText = txtSelCommand.Text
m_SQLDep = New SqlDependency(sqlcmdQuery)
AddHandler m_SQLDep.OnChanged, _ New OnChangedEventHandler(AddressOf SqlDependency_OnChanged)
Dim m_SQLDep As SqlDependency
sqlcmdQuery.CommandText = txtSelCommand.Text
m_SQLDep = New SqlDependency(sqlcmdQuery)
AddHandler m_SQLDep.OnChanged, _ New OnChangedEventHandler(AddressOf SqlDependency_OnChanged)
Marcel Gnoth, NTeam GmbH www.gnoth.net
Event Notification
• Nachricht versenden, wenn bestimmte Ereignisse auftreten
• Ähnlich den Triggern• Es wird kein Code ausgeführt
– Nachricht wird an Service Broker übergeben– Und an eine Queue geschickt
• DDL, DML und einige Trace Ereignisse
CREATE QUEUE evtDdlNotif WITH STATUS = ON
--then we can create the serviceCREATE SERVICE evtDdlService ON QUEUE evtDdlNotif--this is a MS supplied contract([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
CREATE EVENT NOTIFICATION ddlEvents ON DATABASEFOR DDL_DATABASE_LEVEL_EVENTSTO SERVICE evtDdlService
select cast(message_body as nvarchar(MAX)),* from evtDdlNotif
CREATE QUEUE evtDdlNotif WITH STATUS = ON
--then we can create the serviceCREATE SERVICE evtDdlService ON QUEUE evtDdlNotif--this is a MS supplied contract([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
CREATE EVENT NOTIFICATION ddlEvents ON DATABASEFOR DDL_DATABASE_LEVEL_EVENTSTO SERVICE evtDdlService
select cast(message_body as nvarchar(MAX)),* from evtDdlNotif
Marcel Gnoth, NTeam GmbH www.gnoth.net
Demo
Event Notification
Marcel Gnoth, NTeam GmbH www.gnoth.net
Typische SSB Applikation
• Nicht nur TSQL• Komplexe Prozeduren in Yukon• Clientzugriffe über ADO.Net• Kombinieren mit Query Notifications
SQL Server
Workstation A Workstation B
SSB1 SSB2
SQL Server
SSB1
Server Applikation
Workstation C Workstation D
Marcel Gnoth, NTeam GmbH www.gnoth.net
Und noch ein Queuing System
SSB / MSMQ
Marcel Gnoth, NTeam GmbH www.gnoth.net
MSMQ / SSB
• SSB für hohe Performance designed• Integriert in die DB• Solange nur lokal, kein DTC -> schnelle Tx
• MSMQ für komponentenbasierte Systeme– COM+, Enterprise Services– Kann mit SQL Tx kombiniert werden
• Overhead• DTC
• Messageing zwischen DB‘s -> SSB– Auch SW Komponenten könnten SSB verwenden
• Messaging zwischen Komponenten -> MSMQ– Hat auch spezielle Features
Marcel Gnoth, NTeam GmbH www.gnoth.net
Fazit
• Zielgruppe– Große DBs– Komplexe, langwierige Transaktionen
• Entkoppelung von Systemen und Transaktionen• Für asynchrone Kommunikation zwischen DBs
– Kein DTC solange nur mit einer DB Instanz gearbeitet wird
• Ersetzt nicht MSMQ– MSMQ für asynchrone Kommunikation von
Softwarekomponenten
• Es gibt Überschneidungen
Marcel Gnoth, NTeam GmbH www.gnoth.net
Ressourcen
• Developer Spothttp://www.sqlservicebroker.com/forums/
• Newsgrouphttp://communities.microsoft.com/newsgroups/default.asp?icp=sqlserver2005&slcid=us
• Event Notificationshttp://www.informit.com/articles/article.asp?p=327394&seqNum=5
• A First Look at SQL Server 2005 Service Brokerhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsql90/html/sqlsvcbroker.asp
• Bloghttp://www.geekswithblogs.net/veerji/articles/12913.aspx
Marcel Gnoth, NTeam GmbH www.gnoth.net
Alles wird gut
Uff...Uff...