博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sql broker_使用SQL Server Service Broker进行异步处理
阅读量:2513 次
发布时间:2019-05-11

本文共 9663 字,大约阅读时间需要 32 分钟。

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的对象资源管理器中的不同类型的对象。

SQL Service Broker objects in the SQL Server Management Studio,

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 ReceivedOrdersAUTHORIZATION dboVALIDATION = 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 OrderQueueWITH 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 OrderServiceAUTHORIZATION 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对象。

SQL Service Broker objects in the SQL Server Management Studio after creating them.

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)  )ASBEGIN  DECLARE @OrderDate AS SMALLDATETIME  SET @OrderDate = GETDATE()  DECLARE @XMLMessage XML   CREATE 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 Table  INSERT INTO Orders (    OrderID    ,OrderDate    ,ProductCode    ,Quantity    ,UnitPrice    )  VALUES (    @OrderID    ,@OrderDate    ,@ProductCode    ,@Quantity    ,@UnitPrice    )     --Creating the XML Message  SELECT @XMLMessage = (      SELECT *      FROM #Message      FOR XML PATH('Order')        ,TYPE      );   DECLARE @Handle UNIQUEIDENTIFIER;  --Sending the Message to the Queue  BEGIN    DIALOG CONVERSATION @Handle    FROM 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.50 usp_CreateOrders 202003,'PD0002',2,100.75 usp_CreateOrders 202003,'PD0010',1.5,20.00

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

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

Order table after records are inserted.

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,statusFROM 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 XML DECLARE @OrderDate DATE DECLARE @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 1000 SET @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 @OrderIDPRINT @OrderDatePRINT @ProductCodePRINT @QuantityPRINT @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用于异步处理。

翻译自:

sql broker

转载地址:http://bsswd.baihongyu.com/

你可能感兴趣的文章
正则表达式的搜索和替换
查看>>
个人项目:WC
查看>>
地鼠的困境SSL1333 最大匹配
查看>>
flume+elasticsearch+kibana遇到的坑
查看>>
【MM系列】在SAP里查看数据的方法
查看>>
C#——winform
查看>>
CSS3 transform制作的漂亮的滚动式导航
查看>>
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
电梯调度程序的UI设计
查看>>
转自 zera php中extends和implements的区别
查看>>
Array.of使用实例
查看>>
【Luogu】P2498拯救小云公主(spfa)
查看>>
如何获取网站icon
查看>>
几种排序写法
查看>>
java 多线程的应用场景
查看>>
dell support
查看>>