Configuring Service Broker for Asynchronous Processing
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的更多相关文章
- Reusing dialogs with a dialog pool--一个sql server service broker例子
一个sql server service broker例子 ----------------------------------- USE master GO -------------------- ...
- 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 ...
- 基于SQL Server 2008 Service Broker构建企业级消息系统
注:这篇文章是为InfoQ 中文站而写,文章的地址是:http://www.infoq.com/cn/articles/enterprisemessage-sqlserver-servicebroke ...
- Service Broker应用(2):不同server间的数据传输,包含集群
不同Server之间的数据传输,包含DB使用AlwaysOn 配置脚本: SQL Server Service Broker 跨集群通信 具体的TSQL 脚本语句如下.注意的是TSQL语句是在发送方还 ...
- Service Broker应用(1):简介、同server不同DB间的数据传输
简介:SQL Server Service Broker,以下简称SSB,是一种完全基于MSSQL数据库的数据处理技术,为短时间内处理大量数据提供了一种可靠.稳定.高效的解决方案.一次同步的数据最大可 ...
- 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 ...
- MSSQL数据库链接字符串Asynchronous Processing=true不是异步查询吗,怎么是缓存
;Asynchronous Processing=true 不是异步查询吗,怎么是缓存 <!--<add name="default" providerName=&q ...
- BizTalk 开发系列(四十) BizTalk WCF-SQL Adapter读取SQL Service Broker消息
SQL Service Broker 是在SQL Server 2005中新增的功能.Service Broker 为 SQL Server 提供队列和可靠的消息传递,可以可用来建立以异步消息为基础的 ...
- SQL Server 2005 Service Broker
一.引言 SQL Server 2005 的一个主要成就是可以实现可靠.可扩展且功能完善的数据库应用程序.与 .NET Framework 2.0 公共语言运行库 (CLR) 的集成使开发人员可以将重 ...
随机推荐
- Cocos2dx.3x入门三部曲-Hello Game项目解析(三)
一.前提: 完成Hello Game项目的创建编译. 具体参考:Cocos2dx.3x_Hello Game项目创建篇 二.本篇目标: l 分析proj.win32工程的主要构成 l 分析proj ...
- 今天踩过的坑——structs和spring
struts 如果实现了CookiesAware了,还需要引用org.apache.struts2.interceptor.CookieInterceptor过滤器,否则拿不到值同时还要能看到这样的错 ...
- 更多文章请访问"程序旅途”
更多文章请访问我的个人独立博客 程序旅途
- Eclipse中web项目缓存路径
eclipse运行web项目后, 默认保存到 workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps ecli ...
- Codeforces Round #384 (Div. 2) C. Vladik and fractions 构造题
C. Vladik and fractions 题目链接 http://codeforces.com/contest/743/problem/C 题面 Vladik and Chloe decided ...
- asp.net 多个文件同时下载
1.首先读取文件夹下的文件,可能同时存在多个文件 2.选中文件,然后点击下载,同时可以选择多个文件. 思路:通过生产压缩包的形式进行下载,然后再清楚压缩包,这样用户可以一次性全部下载下来. 一.获取目 ...
- 提高FOR插入数据库动作的优化代码
await Task.Factory.StartNew(() => Parallel.ForEach(result.data.o, s => { sql = "insert in ...
- Mac OSX 安装nvm(node.js版本管理器)
我的系统 1.打开github官网https://github.com/,输入nvm搜索,选择creationix/nvm,打开 2.找到Install script,复制 curl -o- http ...
- EETOP中关于Gm仿真的一些帖子的总结
1. cadence画gm曲线 电路里,要把漏的电源dc值设置成变量,比如叫vds,计算器,info标签,点op,然后点管子,在op窗口点list,选gm,然后把这个公式弄到ADE的outputs那里 ...
- 3种归并操作js代码
/**良哥的*/ function merge(a, b) { var aLen = a.length, bLen = b.length, maxLen = Math.max(aLen, bLen), ...