Configuring Service Broker for Asynchronous Processing

--create a database and enable the database for Service Broker usage

CREATE DATABASE AsyncProcessingDemo;
GO IF (SELECT is_broker_enabled FROM sys.databases WHERE name = N'AsyncProcessingDemo') = 0
BEGIN
ALTER DATABASE AsyncProcessingDemo SET ENABLE_BROKER;
END
GO USE AsyncProcessingDemo;
GO --=========================================================================================================
--Configuring broker components
-- Create the message types
CREATE MESSAGE TYPE [AsyncRequest] VALIDATION = WELL_FORMED_XML;
CREATE MESSAGE TYPE [AsyncResult] VALIDATION = WELL_FORMED_XML; -- Create the contract
CREATE CONTRACT [AsyncContract]
(
[AsyncRequest] SENT BY INITIATOR,
[AsyncResult] SENT BY TARGET
); -- Create the processing queue and service - specify the contract to allow sending to the service
CREATE QUEUE ProcessingQueue;
CREATE SERVICE [ProcessingService] ON QUEUE ProcessingQueue ([AsyncContract]); -- Create the request queue and service
CREATE QUEUE RequestQueue;
CREATE SERVICE [RequestService] ON QUEUE RequestQueue; --=========================================================================================================
--Sending a Message for Processing
-- Create the wrapper procedure for sending messages
CREATE PROCEDURE dbo.SendBrokerMessage
@FromService SYSNAME,
@ToService SYSNAME,
@Contract SYSNAME,
@MessageType SYSNAME,
@MessageBody XML
AS
BEGIN
SET NOCOUNT ON; DECLARE @conversation_handle UNIQUEIDENTIFIER; BEGIN TRANSACTION; BEGIN DIALOG CONVERSATION @conversation_handle
FROM SERVICE @FromService
TO SERVICE @ToService
ON CONTRACT @Contract
WITH ENCRYPTION = OFF; SEND ON CONVERSATION @conversation_handle
MESSAGE TYPE @MessageType(@MessageBody); COMMIT TRANSACTION;
END
GO -- Send a request
EXECUTE dbo.SendBrokerMessage
@FromService = N'RequestService',
@ToService = N'ProcessingService',
@Contract = N'AsyncContract',
@MessageType = N'AsyncRequest',
@MessageBody = N'<AsyncRequest><AccountNumber>12345</AccountNumber></AsyncRequest>'; -- Check for message on processing queue
SELECT CAST(message_body AS XML) FROM ProcessingQueue;
GO --=========================================================================================================
--Processing Messages
-- Create processing procedure for processing queue
CREATE PROCEDURE dbo.ProcessingQueueActivation
AS
BEGIN
SET NOCOUNT ON; DECLARE @conversation_handle UNIQUEIDENTIFIER;
DECLARE @message_body XML;
DECLARE @message_type_name sysname; WHILE (1=1)
BEGIN
BEGIN TRANSACTION; WAITFOR
(
RECEIVE TOP (1)
@conversation_handle = conversation_handle,
@message_body = CAST(message_body AS XML),
@message_type_name = message_type_name
FROM ProcessingQueue
), TIMEOUT 5000; IF (@@ROWCOUNT = 0)
BEGIN
ROLLBACK TRANSACTION;
BREAK;
END IF @message_type_name = N'AsyncRequest'
BEGIN
-- Handle complex long processing here
-- For demonstration we'll pull the account number and send a reply back only DECLARE @AccountNumber INT = @message_body.value('(AsyncRequest/AccountNumber)[1]', 'INT'); -- Build reply message and send back
DECLARE @reply_message_body XML = N'
' + CAST(@AccountNumber AS NVARCHAR(11)) + '
'; SEND ON CONVERSATION @conversation_handle
MESSAGE TYPE [AsyncResult] (@reply_message_body);
END -- If end dialog message, end the dialog
ELSE IF @message_type_name = N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'
BEGIN
END CONVERSATION @conversation_handle;
END -- If error message, log and end conversation
ELSE IF @message_type_name = N'http://schemas.microsoft.com/SQL/ServiceBroker/Error'
BEGIN
-- Log the error code and perform any required handling here
-- End the conversation for the error
END CONVERSATION @conversation_handle;
END COMMIT TRANSACTION;
END
END
GO -- Create procedure for processing replies to the request queue
CREATE PROCEDURE dbo.RequestQueueActivation
AS
BEGIN
SET NOCOUNT ON; DECLARE @conversation_handle UNIQUEIDENTIFIER;
DECLARE @message_body XML;
DECLARE @message_type_name sysname; WHILE (1=1)
BEGIN
BEGIN TRANSACTION; WAITFOR
(
RECEIVE TOP (1)
@conversation_handle = conversation_handle,
@message_body = CAST(message_body AS XML),
@message_type_name = message_type_name
FROM RequestQueue
), TIMEOUT 5000; IF (@@ROWCOUNT = 0)
BEGIN
ROLLBACK TRANSACTION;
BREAK;
END IF @message_type_name = N'AsyncResult'
BEGIN
-- If necessary handle the reply message here
DECLARE @AccountNumber INT = @message_body.value('(AsyncResult/AccountNumber)[1]', 'INT'); -- Since this is all the work being done, end the conversation to send the EndDialog message
END CONVERSATION @conversation_handle;
END -- If end dialog message, end the dialog
ELSE IF @message_type_name = N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'
BEGIN
END CONVERSATION @conversation_handle;
END -- If error message, log and end conversation
ELSE IF @message_type_name = N'http://schemas.microsoft.com/SQL/ServiceBroker/Error'
BEGIN
END CONVERSATION @conversation_handle;
END COMMIT TRANSACTION;
END
END
GO --=========================================================================================================
--Testing the Procedures
-- Process the message from the processing queue
EXECUTE dbo.ProcessingQueueActivation;
GO -- Check for reply message on request queue
SELECT CAST(message_body AS XML) FROM RequestQueue;
GO -- Process the message from the request queue
EXECUTE dbo.RequestQueueActivation;
GO --=========================================================================================================
--Automating the Processing
-- Alter the processing queue to specify internal activation
ALTER QUEUE ProcessingQueue
WITH ACTIVATION
(
STATUS = ON,
PROCEDURE_NAME = dbo.ProcessingQueueActivation,
MAX_QUEUE_READERS = 10,
EXECUTE AS SELF
);
GO -- Alter the request queue to specify internal activation
ALTER QUEUE RequestQueue
WITH ACTIVATION
(
STATUS = ON,
PROCEDURE_NAME = dbo.RequestQueueActivation,
MAX_QUEUE_READERS = 10,
EXECUTE AS SELF
);
GO -- Test automated activation
-- Send a request EXECUTE dbo.SendBrokerMessage
@FromService = N'RequestService',
@ToService = N'ProcessingService',
@Contract = N'AsyncContract',
@MessageType = N'AsyncRequest',
@MessageBody = N'<AsyncRequest><AccountNumber>12345</AccountNumber></AsyncRequest>'; -- Check for message on processing queue
-- nothing is there because it was automatically processed
SELECT CAST(message_body AS XML) FROM ProcessingQueue;
GO -- Check for reply message on request queue
-- nothing is there because it was automatically processed
SELECT CAST(message_body AS XML) FROM RequestQueue;
GO

转自:https://sqlperformance.com/2014/03/sql-performance/configuring-service-broker

Configuring Service Broker for Asynchronous Processing的更多相关文章

  1. Reusing dialogs with a dialog pool--一个sql server service broker例子

    一个sql server service broker例子 ----------------------------------- USE master GO -------------------- ...

  2. The SQL Server Service Broker for the current database is not enabled

    把一个数据恢复至另一个服务器上,出现了一个异常: The SQL Server Service Broker for the current database is not enabled, and ...

  3. 基于SQL Server 2008 Service Broker构建企业级消息系统

    注:这篇文章是为InfoQ 中文站而写,文章的地址是:http://www.infoq.com/cn/articles/enterprisemessage-sqlserver-servicebroke ...

  4. Service Broker应用(2):不同server间的数据传输,包含集群

    不同Server之间的数据传输,包含DB使用AlwaysOn 配置脚本: SQL Server Service Broker 跨集群通信 具体的TSQL 脚本语句如下.注意的是TSQL语句是在发送方还 ...

  5. Service Broker应用(1):简介、同server不同DB间的数据传输

    简介:SQL Server Service Broker,以下简称SSB,是一种完全基于MSSQL数据库的数据处理技术,为短时间内处理大量数据提供了一种可靠.稳定.高效的解决方案.一次同步的数据最大可 ...

  6. The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported.

    当Insus.NET尝试解决此问题<When using SqlDependency without providing an options value, SqlDependency.Star ...

  7. MSSQL数据库链接字符串Asynchronous Processing=true不是异步查询吗,怎么是缓存

    ;Asynchronous Processing=true  不是异步查询吗,怎么是缓存 <!--<add name="default" providerName=&q ...

  8. BizTalk 开发系列(四十) BizTalk WCF-SQL Adapter读取SQL Service Broker消息

    SQL Service Broker 是在SQL Server 2005中新增的功能.Service Broker 为 SQL Server 提供队列和可靠的消息传递,可以可用来建立以异步消息为基础的 ...

  9. SQL Server 2005 Service Broker

    一.引言 SQL Server 2005 的一个主要成就是可以实现可靠.可扩展且功能完善的数据库应用程序.与 .NET Framework 2.0 公共语言运行库 (CLR) 的集成使开发人员可以将重 ...

随机推荐

  1. JVM中的垃圾收集算法和Heap分区简记

    如何判断垃圾对象? 垃圾收集的第一步就是先需要算法来标记哪些是垃圾,然后再对垃圾进行处理.   引用计数(ReferenceCounting)算法 这种方法比较简单直观,FlashPlayer/Pyt ...

  2. 从一个例子中体会React的基本面

    [起初的准备工作] npm init npm install --save react react-dom npm install --save-dev html-webpack-plugin web ...

  3. maven nexus-staging-maven-plugin exception-connect timed out

    不知道是国内的网络的问题还是别的原因,在deploy一个maven的artifact到oss server的时候总是报错: Failed to execute goal org.sonatype.pl ...

  4. AngularJS Eclipse——新手入门【翻译+整理】

    原文地址 本文介绍如何安装和配置 AngularJS Eclipse.AngularJS Eclipse 插件是基于强大的 JavaScript 推断引擎(javascript inference e ...

  5. WPF 创建桌面快捷方式

    #region 创建桌面快捷方式 string deskTop = System.Environment.GetFolderPath(System.Environment.SpecialFolder. ...

  6. [JWT] AngularJS Authentication with JWT

    Set up server for JWT Authentication 1. require express 2. require faker: If faker is not install ye ...

  7. 用户控件的设计要点 System.Windows.Forms.UserControl

    用户控件的设计要点 最近的项目中有一个瀑布图(彩图)的功能,就是把空间和时间上的点量值以图的形式呈现出来,如下图: X坐标为空间,水平方向的一个像素代表一个空间单位(例如50米) Y坐标为时间,垂直方 ...

  8. Cubieboard2裸机开发之(二)板载LED交替闪烁

    前言 电路原理在文章http://www.cnblogs.com/lknlfy/p/3583806.html中已经说明,两个LED的原理图是一样的.要使两个LED交替闪烁,只需要在点亮蓝色LED,熄灭 ...

  9. Java Web 工作技巧总结 16.8

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! 四时不谢之兰,百节长青之竹,万古不败之石,千秋不变之人. 1. AOP – LOG项目中,一个请 ...

  10. UIWebView 操作

    网络开发中,当公司已经使用 HTML5 技术实现同时适应 Android 和 iOS 等多个平台的网页时,这时往往需要我们 iOS 平台能够嵌入网页并进行各种交互,那我们应该怎么做来实现这种需求呢? ...