sql broker

介绍 (Introduction)

In the real-world implementation of SQL Server of an enterprise system, it always needs to implement data in multiple databases. In most of the cases, a single transaction will span across multiple databases. If there are multiple databases, there will be performance issues and implementation issues during the cross-database transactions. However, with the use of SQL Service Broker that was introduced in SQL Server 2005, you can implement asynchronous transactions between databases.

在企业系统SQL Server的实际实现中,始终需要在多个数据库中实现数据。 在大多数情况下,单个事务将跨越多个数据库。 如果有多个数据库,则在跨数据库事务期间将存在性能问题和实现问题。 但是,通过使用SQL Server 2005中引入SQL Service Broker,可以在数据库之间实现异步事务。

什么是服务经纪人 (What is Service Broker)

The Service broker is similar to other message queuing technologies such as MSMQ. In the service broker, data can be processed automatically or on-demand. Data in the SQL service broker is consumed by SEND and RECEIVE, which is typically an XML format.

服务代理类似于其他消息排队技术,例如MSMQ。 在服务代理中,可以自动或按需处理数据。 SQL服务代理中的数据由SEND和RECEIVE使用,通常是XML格式。

Service Broker的方案 (A scenario for Service Broker)

Though there are a few other implementations of Service Broker, we will be looking at the usage of Service Broker for the Distributed Transaction System.

尽管还有其他一些Service Broker的实现,但我们将研究Service Broker在分布式事务系统中的用法。

Let us assume that there is an Order System. When the order is received, inventory has to be processed. To maintain scalability and security concerns, these are handled by two processes.

让我们假设有一个订单系统。 收到订单后,必须处理库存。 为了保持可伸缩性和安全性考虑,这些由两个过程处理。

We will start by enabling the service broker from the following code.

我们将从以下代码启用服务代理开始。

ALTER DATABASE OrderDB
SET ENABLE_BROKER;

In the service broker, we will be using four main concepts: Message Type, Contract, Queue, and Services. The following figure shows different types of objects in Object Explorer for SQL service broker.

在服务代理中,我们将使用四个主要概念:消息类型,合同,队列和服务。 下图显示了用于SQL Service Broker的对象资源管理器中的不同类型的对象。

However, to create relevant service broker objects, you need to use T-SQL queries as there is no user interface for those object creations.

但是,要创建相关的服务代理对象,您需要使用T-SQL查询,因为没有用于这些对象创建的用户界面。

Let’s create a Message Type. A Message type will define what type of data you are sending.

让我们创建一个消息类型。 消息类型将定义您要发送的数据类型。

CREATE MESSAGE TYPE ReceivedOrders
AUTHORIZATION dbo
VALIDATION = None

Above created message type ReceviedOrders are owned by dbo, and validation is set to none. In the SQL service broker, there can be four types of validations, such as NONE, EMPTY, WELL_FORMED_XML, and VALID_XML WITH SCHEMA COLLECTION. In the NONE option, no validations are made, and typically NONE is used as validation left to the consumption.

上面创建的消息类型ReceviedOrders由dbo拥有,并且验证设置为none。 在SQL服务代理中,可以有四种验证类型,例如NONE,EMPTY,WELL_FORMED_XML和VALID_XML WITH SCHEMA COLLECTION。 在NONE选项中,不进行任何验证,通常将NONE用作消耗的验证。

The next service broker object that we create is the CONTRACT. The contract will create a logical grouping of one or more message types. This means that there is a one-to-many relationship between the CONTRACT and the MESSAGE TYPE.

我们创建的下一个服务代理对象是CONTRACT。 合同将创建一个或多个消息类型的逻辑分组。 这意味着“合同”和“消息类型”之间存在一对多的关系。

CREATE CONTRACT postmessages
(ReceivedOrders SENT BY ANY)

In the above-created CONTRACT, it has specified that messages can be sent from any endpoints. However, if you want to restrict for security purposes, you still have the option of restricting it.

在上面创建的CONTRACT中,它指定可以从任何端点发送消息。 但是,如果出于安全考虑要进行限制,则仍然可以选择对其进行限制。

Next, we will be creating an important object called QUEUE that will hold the messages that you are sending.

接下来,我们将创建一个名为QUEUE的重要对象,该对象将保存您正在发送的消息。

CREATE QUEUE OrderQueue
WITH STATUS = ON, RETENTION = OFF

When the status is set to OFF, you cannot send or receive messages from the queue. Another important configuration is that the RETENTION option. If the RETENTION is set to OFF, messages will be deleted from the queue. If you want to keep the messages for auditing purposes, you can set this to ON. However, setting the RETENTION to ON will impact the performance of the system. Therefore, it is recommended to set the RETENTION to OFF.

当状态设置为OFF时,您将无法从队列发送或接收消息。 另一个重要的配置是RETENTION选项。 如果RETENTION设置为OFF,则消息将从队列中删除。 如果要保留消息以用于审核,可以将其设置为ON。 但是,将“保留”设置为“开”会影响系统的性能。 因此,建议将RETENTION设置为OFF。

The final SQL Service broker object to cover for our scenario is the SERVICE. Service will ensure that messages are sending and receiving.

本方案要覆盖的最终SQL Service代理对象是SERVICE。 服务将确保邮件正在发送和接收。

CREATE SERVICE OrderService
AUTHORIZATION dbo
ON QUEUE OrderQueue
(postmessages)

The service will contain the queue and the contract, as shown in the above code.

该服务将包含队列和合同,如上面的代码所示。

Now let’s see how you can see the created SQL Service Broker objects in the SQL Server Management Studio (SSMS).

现在,让我们看看如何在SQL Server Management Studio(SSMS)中查看创建SQL Service Broker对象。

Now we have set up the infrastructure to message queues, and let’s see how we can use them. We will create a table called Orders, as shown below.

现在,我们已经建立了消息队列的基础结构,让我们看看如何使用它们。 我们将创建一个名为Orders的表,如下所示。

CREATE TABLE [dbo].[Orders]([OrderID] [int] NOT NULL,[OrderDate] [date] NULL,[ProductCode] [varchar](50) NOT NULL,[Quantity] [numeric](9, 2) NULL,[UnitPrice] [numeric](9, 2) NULL,CONSTRAINT [PK__Orders] PRIMARY KEY CLUSTERED
([OrderID] ASC,[ProductCode] ASC
)
ON [PRIMARY]
) ON [PRIMARY]
GO

We will create a Stored Procedure that will insert records to the Order table and send the message to the previously defined queue.

我们将创建一个存储过程,该存储过程将在Order表中插入记录,并将消息发送到先前定义的队列。

CREATE PROCEDURE usp_CreateOrders (@OrderID INT,@ProductCode VARCHAR(50),@Quantity NUMERIC(9, 2),@UnitPrice NUMERIC(9, 2))
AS
BEGINDECLARE @OrderDate AS SMALLDATETIMESET @OrderDate = GETDATE()DECLARE @XMLMessage XMLCREATE TABLE #Message (OrderID INT PRIMARY KEY,OrderDate DATE,ProductCode VARCHAR(50),Quantity NUMERIC(9, 2),UnitPrice NUMERIC(9, 2))INSERT INTO #Message (OrderID,OrderDate,ProductCode,Quantity,UnitPrice)VALUES (@OrderID,@OrderDate,@ProductCode,@Quantity,@UnitPrice)--Insert to Orders TableINSERT INTO Orders (OrderID,OrderDate,ProductCode,Quantity,UnitPrice)VALUES (@OrderID,@OrderDate,@ProductCode,@Quantity,@UnitPrice)--Creating the XML MessageSELECT @XMLMessage = (SELECT *FROM #MessageFOR XML PATH('Order'),TYPE);DECLARE @Handle UNIQUEIDENTIFIER;--Sending the Message to the QueueBEGINDIALOG CONVERSATION @HandleFROM SERVICE OrderService TO SERVICE 'OrderService' ON CONTRACT [postmessages]WITH ENCRYPTION = OFF;SEND ON CONVERSATION @Handle MESSAGE TYPE ReceivedOrders(@XMLMessage);END GO

In the above-stored procedure, SEND command is used to send an XML formatted message to the ReceivedOrders queue.

在以上存储的过程中,SEND命令用于将XML格式的消息发送到ReceivedOrders队列。

Let us execute this stored procedure with the following queries.

让我们通过以下查询执行此存储过程。

 usp_CreateOrders 202003,'PD0001',1,10.50usp_CreateOrders 202003,'PD0002',2,100.75usp_CreateOrders 202003,'PD0010',1.5,20.00

When the above execution are completed you will see three records in the Orders table.

完成上述执行后,您将在Orders表中看到三个记录。

Since we have sent three messages to the OrderQueue, we can verify those entries from the following query.

由于我们已经向OrderQueue发送了三个消息,因此我们可以从以下查询中验证这些条目。

SELECT service_name
,priority,
queuing_order,
service_contract_name,
message_type_name,
validation,
message_body,
message_enqueue_time,
status
FROM dbo.OrderQueue

Message body cannot be viewed as it is encrypted as shown below.

邮件正文如下所示被加密,因此无法查看。

Now let’s consume the queue from the following code.

现在,让我们使用以下代码处理队列。

DECLARE @Handle UNIQUEIDENTIFIER ;DECLARE @MessageType SYSNAME ;DECLARE @Message XMLDECLARE @OrderDate DATEDECLARE @OrderID INT DECLARE @ProductCode VARCHAR(50)DECLARE @Quantity NUMERIC (9,2)DECLARE @UnitPrice NUMERIC (9,2)WAITFOR( RECEIVE TOP (1)
@Handle = conversation_handle,
@MessageType = message_type_name,
@Message = message_body FROM dbo.OrderQueue),TIMEOUT 1000SET @OrderID   =   CAST(CAST(@Message.query('/Order/OrderID/text()') AS NVARCHAR(MAX)) AS INT)
SET @OrderDate   =   CAST(CAST(@Message.query('/Order/OrderDate/text()') AS NVARCHAR(MAX)) AS DATE)
SET @ProductCode =   CAST(CAST(@Message.query('/Order/ProductCode/text()') AS NVARCHAR(MAX)) AS VARCHAR(50))
SET @Quantity    =   CAST(CAST(@Message.query('/Order/Quantity/text()') AS NVARCHAR(MAX)) AS NUMERIC(9,2))
SET @UnitPrice   =   CAST(CAST(@Message.query('/Order/UnitPrice/text()') AS NVARCHAR(MAX)) AS NUMERIC(9,2))PRINT @OrderID
PRINT @OrderDate
PRINT @ProductCode
PRINT @Quantity
PRINT @UnitPrice

The above code can consume the data in the queue and process them. With this approach, asynchronous processing can be done.

上面的代码可以使用队列中的数据并进行处理。 使用这种方法,可以完成异步处理。

额外的好处 (Additional Benefits)

Apart from the asynchronous processing, other benefits can be achieved from the SQL service broker. One of the important features is that messages are within the database. If you backup and restore the database, messages of the queues are retained.

除了异步处理之外,SQL服务代理还可以带来其他好处。 重要功能之一是消息位于数据库内。 如果备份和还原数据库,则会保留队列中的消息。

Further, in SQL Server, database mail uses the SQL service broker feature.

此外,在SQL Server中,数据库邮件使用SQL服务代理功能。

结论 (Conclusion)

SQL Server Service broker is an important component in the SQL Server family that can be used for various activities. In this article, it was explained how SQL service broker was used for asynchronous processing using MESSAGE TYPE, CONTRACT, QUEUE, and SERVICES.

SQL Server服务代理是SQL Server系列中的重要组件,可用于各种活动。 在本文中,解释了如何使用MESSAGE TYPE,CONTRACT,QUEUE和SERVICES将SQL Service Broker用于异步处理。

翻译自: https://www.sqlshack.com/using-the-sql-server-service-broker-for-asynchronous-processing/

sql broker

sql broker_使用SQL Server Service Broker进行异步处理相关推荐

  1. 未启用当前数据库的 SQL Server Service Broker,因此查询通知不受支持。如果希望使用通知,请为此数据库启用 Service Broker...

    昨晚遇到的这个问题,也知道Notifications service依赖底层的Service broker的.本以为只需要执行以下脚本对数据库启用Service broker即可. alter dat ...

  2. 错误:未启用当前数据库的SQL Server Service Broker,因此查询通知不受支持。如果希望使用通知,请为此数据库启用 Service Broker。...

    解决方法: 打开SQL Server,新建查询: ALTER DATABASE 数据库名 SET NEW_BROKER WITH ROLLBACK IMMEDIATE; ALTER DATABASE ...

  3. 未启用当前数据库的 SQL Server Service Broker

    alter database 数据库名 set enable_broker select IS_BROKER_ENABLED from master.sys.databases where name= ...

  4. SQL Server 2005 Service Broker 初探

    发布日期 : 11/4/2004| 更新日期 : 11/4/2004 Roger Wolter 适用于: Microsoft SQL Server 2005 Transact SQL (T-SQL) ...

  5. SQL Server 2012 中的 Service Broker功能的一些改进或增强

    1. 可以将消息发送到多个目标服务(多播) 通过支持多个会话句柄,扩展了 SEND (Transact-SQL) 语句的语法以启用多播. DECLARE @dialog_handle1 UNIQUEI ...

  6. SQL Server 2005 Service Broker 初探 [摘抄]

    <!----> <!--Content type: DocStudio. Transform: devdiv2mtps.xslt.--> 发布日期 : 11/4/2004| 更 ...

  7. [转]基于SQL Server 2008 Service Broker构建企业级消息系统

    http://www.infoq.com/cn/articles/enterprisemessage-sqlserver-servicebroker 1.引言 Microsoft 在SQL Serve ...

  8. RDS SQL Server死锁(Deadlock)系列之四利用Service Broker事件通知捕获死锁

    问题引入 在前面三篇文章,我们分别谈到了使用DBCC命令捕获死锁:使用Profiler界面跟踪Deadlock Graph事件捕获死锁和使用脚本自动部署Profiler Trace捕获死锁.这篇文章介 ...

  9. SQL Server 2005自带的Service Broker功能

    --Service Broker 简介 Service Broker是使SQL Server成为一个构建可靠的分布式异步应用程序平台. Service Broker并不是一个通用的消息处理系统. Se ...

最新文章

  1. AI一分钟 | 李开复:AI创业公司估值今年会降20%~30%;谷歌让搜索结果加载速度提升两倍...
  2. 在华为笔记本 MateBook 13 (MX250)上配置yolo-v3_tensorflow CUDA 所遇到的一些坑(cuda无法识别显卡)
  3. Java反射机制的适用场景及其利与弊 ***
  4. openssl 测试加密卡_OpenSSL自带的aes_128_ecb加密函数——密文长度测试
  5. find VS not looking for VS2015
  6. Java 蓝桥杯 算法 和为T
  7. Linux网络报文捕获/抓包技术对比:napi、libpcap、afpacket、PF_RING、PACKET_MMAP、DPDK、XDP(eXpress Data Path)
  8. Spring mvc 组件
  9. Python基础----Matplotlib
  10. html显示数据库的数据类型,将HTML插入mysql数据库,显示E类型
  11. 基于模拟退火算法求解TSP问题(JAVA)
  12. 计算机excel函数lookup,详细介绍数据查找VLookup函数在Excel中的应用举例
  13. 博图可以用c语言编程吗,S7300能用C语言编程吗?
  14. 驱动开发:BSOD 0xC4_f6 句柄问题
  15. 绿盟 java 面试_绿盟科技校园招聘面试经验|面试问题(共52条)- 职业圈
  16. (web前端每日一练)用JavaScript制作一个跟随鼠标的小球炫彩动画 /doge/doge
  17. 使用c语言实现后缀表达式计算器
  18. 苹果手机有护眼模式吗_调节手机明暗度能起到护眼模式一样的效果?
  19. 尚硅谷-SpringSecurity
  20. 一年经验的java程序员薪资有多少?java收入分级

热门文章

  1. 示例 - 10行代码在C#中获取页面元素布局信息
  2. Tomcat的部署+第一个Servlet
  3. python正则表达式之re模块方法介绍
  4. mysql 插入数据后返回当前的自增ID方法
  5. Something about TFS
  6. SQL Server Agent 服务启动后又停止
  7. ionic 1页面跳转登录页面后,返回按钮处理
  8. 计算机网络学习笔记(28. Email消息格式与POP协议)
  9. Unity如何刚体控制物体的移动以及旋转
  10. 句句真研—每日长难句打卡Day18