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. 多功能表单填报系统V1.2.1-适用于在线报名系统、调查、数据收集等

    多功能表单系统V1.2.1    前台:http://www.schoolms.net/mysoft/biaodan/index.asp 后台:http://www.schoolms.net/myso ...

  2. ubuntu下安装Node.js(源码安装)

    最近使用hexo的过程中出现了问题,中间载nodejs安装的时候也耽误了些许时间,所以在此记录一下安装的过程. 环境:ubuntu14.0.4LTS,安装nodejs版本node-v0.10.36.t ...

  3. 代码生成器Sql Server 和 Mysql 数据库脚本

    经常用到代码生成器,对于取数据脚本做个记录: #region SQL-SqlServer private string SqlTableList = @"SELECT so.name, Co ...

  4. MYSQL INSERT INTO SELECT 不插入重复数据

    INSERT INTO `b_common_member_count` (uid) SELECT uid FROM `b_common_member` WHERE uid NOT IN (SELECT ...

  5. [转] js == 与 === 的区别

    1.对于string,number等基础类型,==和===是有区别的 1)不同类型间比较,==之比较“转化成同一类型后的值”看“值”是否相等,===如果类型不同,其结果就是不等 2)同类型比较,直接进 ...

  6. 倒计时,js

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  7. Oracle存储过程,以逗号分隔字符串传参的处理

    Oracle存储过程,经常会遇见传入的参数是逗号分隔. 处理需要3步: 第一步,创建Type类型 第二部,创建函数 第三部,创建存储过程 代码如下: 第一步: create or replace ty ...

  8. 使用python pylab库 画线

    pylab 提供了比较强大的画图功能,但是函数和参数都比较多,很容易搞混.我们平常使用最多的应该是画线了.下面,简单的对一些常用的划线函数进行了封装,方便使用. # -*- coding: utf-8 ...

  9. “HTTPS”安全在哪里?

    背景 最近基于兴趣学学习了下 HTTPS 相关的知识,在此记录下学习心得. 在上网获取信息的过程中,我们接触最多的信息加密传输方式也莫过于 HTTPS 了.每当访问一个站点,浏览器的地址栏中出现绿色图 ...

  10. Nginx upstream 长连接

    原文: http://bollaxu.iteye.com/blog/900424 Nginx upstream目前只有短连接,通过HTTP/1.0向后端发起连接,并把请求的"Connecti ...