- Service Broker
- When to use Service Broker
- Overview
- Creating services
- Sending messages
- Processing messages
- Where is the documentation for Service Broker?
- What’s new in Service Broker
- Service broker and Azure SQL Managed Instance
- Messages can be sent to multiple target services (multicast)
- Queues expose the message enqueued time
- Компонент Service Broker Service Broker
- Когда следует использовать компонент Service Broker When to use Service Broker
- Обзор Overview
- Создание служб Creating services
- Отправка сообщений Sending messages
- Обработка сообщений Processing messages
- Где найти документацию по компоненту Service Broker? Where is the documentation for Service Broker?
- Новые возможности (компонент Service Broker) What’s new in Service Broker
- Service Broker и Управляемый экземпляр SQL Azure Service broker and Azure SQL Managed Instance
- Сообщения могут отправляться в несколько целевых служб (многоадресная рассылка) Messages can be sent to multiple target services (multicast)
- Очереди предоставляют время нахождения сообщения в очереди Queues expose the message enqueued time
Service Broker
Applies to: SQL Server (all supported versions) Azure SQL Managed Instance
SQL Server Service Broker provide native support for messaging and queuing in the SQL Server Database Engine and Azure SQL Managed Instance. Developers can easily create sophisticated applications that use the Database Engine components to communicate between disparate databases, and build distributed and reliable applications.
When to use Service Broker
Use Service Broker components to implement native in-database asynchronous message processing functionalities. Application developers who use Service Broker can distribute data workloads across several databases without programming complex communication and messaging internals. Service Broker reduces development and test work because Service Broker handles the communication paths in the context of a conversation. It also improves performance. For example, front-end databases supporting Web sites can record information and send process intensive tasks to queue in back-end databases. Service Broker ensures that all tasks are managed in the context of transactions to assure reliability and technical consistency.
Overview
Service Broker is a message delivery framework that enables you to create native in-database service-oriented applications. Unlike classic query processing functionalities that constantly read data from the tables and process them during the query lifecycle, in service-oriented application you have database services that are exchanging the messages. Every service has a queue where the messages are placed until they are processed.
The messages in the queues can be fetched using the Transact-SQL RECEIVE command or by the activation procedure that will be called whenever the message arrives in the queue.
Creating services
Database services are created by using the CREATE SERVICE Transact SQL statement. Service can be associated with the message queue create by using the CREATE QUEUE statement:
Sending messages
Messages are sent on the conversation between the services using the SEND Transact-SQL statement. A conversation is a communication channel that is established between the services using the BEGIN DIALOG Transact-SQL statement.
The message will be sent to the ExpenssesService and placed in dbo.ExpenseQueue . Because there is no activation procedure associated to this queue, the message will remain in the queue until someone reads it.
Processing messages
The messages that are placed in the queue can be selected by using a standard SELECT query. The SELECT statement will not modify the queue and remove the messages. To read and pull the messages from the queue, you can use the RECEIVE Transact-SQL statement.
Once you process all messages from the queue, you should close the conversation using the END CONVERSATION Transact-SQL statement.
Where is the documentation for Service Broker?
The reference documentation for Service Broker is included in the SQL Server documentation. This reference documentation includes the following sections:
See the previously published documentation for Service Broker concepts and for development and management tasks. This documentation is not reproduced in the SQL Server documentation due to the small number of changes in Service Broker in recent versions of SQL Server.
What’s new in Service Broker
Service broker and Azure SQL Managed Instance
Cross-instance service broker message exchange is supported only between Azure SQL Managed Instances:
- CREATE ROUTE : You can’t use CREATE ROUTE with ADDRESS other than LOCAL or DNS name of another SQL Managed Instance. Port specified must be 4022. See CREATE ROUTE.
- ALTER ROUTE : You can’t use ALTER ROUTE with ADDRESS other than LOCAL or DNS name of another SQL Managed Instance. Port specified must be 4022. See See ALTER ROUTE.
Transport security is supported, dialog security is not:
- CREATE REMOTE SERVICE BINDING is not supported.
Service broker is enabled by default and cannot be disabled. The following ALTER DATABASE options are not supported:
No significant changes were introduced in SQL Server 2019 (15.x). The following changes were introduced in SQL Server 2012 (11.x).
Messages can be sent to multiple target services (multicast)
The syntax of the SEND (Transact-SQL) statement has been extended to enable multicast by supporting multiple conversation handles.
Queues expose the message enqueued time
Queues have a new column, message_enqueue_time, that shows how long a message has been in the queue.
Компонент Service Broker Service Broker
Применимо к: Applies to: SQL Server SQL Server (все поддерживаемые версии) SQL Server SQL Server (all supported versions) Управляемый экземпляр SQL Azure Azure SQL Managed Instance Управляемый экземпляр SQL Azure Azure SQL Managed Instance Применимо к: Applies to: SQL Server SQL Server (все поддерживаемые версии) SQL Server SQL Server (all supported versions) Управляемый экземпляр SQL Azure Azure SQL Managed Instance Управляемый экземпляр SQL Azure Azure SQL Managed Instance
SQL Server SQL Server Компонент Service Broker Service Broker предоставляют встроенную поддержку для обмена сообщениями и очередей в Компонент SQL Server Database Engine SQL Server Database Engine и Управляемом экземпляре SQL Azure. Компонент Service Broker Service Broker provide native support for messaging and queuing in the Компонент SQL Server Database Engine SQL Server Database Engine and Azure SQL Managed Instance. Это облегчает разработчикам создание сложных, надежных распределенных приложений, использующих компоненты Компонент Database Engine Database Engine для связи между разнородными базами данных. Developers can easily create sophisticated applications that use the Компонент Database Engine Database Engine components to communicate between disparate databases, and build distributed and reliable applications.
Когда следует использовать компонент Service Broker When to use Service Broker
Используйте компонент Service Broker для реализации собственных функций обработки асинхронных сообщений в базе данных. Use Service Broker components to implement native in-database asynchronous message processing functionalities. Разработчики приложений, использующие компонент Компонент Service Broker Service Broker , могут распределять рабочую нагрузку между несколькими базами данных без программирования сложного взаимодействия и создания внутреннего обмена сообщениями. Application developers who use Компонент Service Broker Service Broker can distribute data workloads across several databases without programming complex communication and messaging internals. Service Broker сокращает разработку и проверочную работу, потому что компонент Компонент Service Broker Service Broker обеспечивает взаимодействие в контексте диалога. Service Broker reduces development and test work because Компонент Service Broker Service Broker handles the communication paths in the context of a conversation. Кроме того, это повышает производительность. It also improves performance. Например, сервер, обслуживающий клиентские запросы базы данных, поддерживающие веб-сайты, может записывать информацию и отправлять ресурсоемкие задачи в очереди серверных баз данных. For example, front-end databases supporting Web sites can record information and send process intensive tasks to queue in back-end databases. Компонент Service Broker Service Broker гарантирует, что управление всеми задачами ведется в контексте транзакций, чтобы обеспечить надежность и техническое единообразие. ensures that all tasks are managed in the context of transactions to assure reliability and technical consistency.
Обзор Overview
Компонент Service Broker — это инфраструктура доставки сообщений, дающая возможность создания ориентированных на службы приложений в базе данных. Service Broker is a message delivery framework that enables you to create native in-database service-oriented applications. В отличие от функциональных возможностей классической обработки, которые требуют постоянно считывать данные из таблиц и обрабатывать их во время жизненного цикла запроса, в ориентированных на службы приложениях имеются службы базы данных, которые позволяют обмениваться сообщениями. Unlike classic query processing functionalities that constantly read data from the tables and process them during the query lifecycle, in service-oriented application you have database services that are exchanging the messages. Каждая служба имеет очередь, куда помещаются сообщения до их обработки. Every service has a queue where the messages are placed until they are processed.
Сообщения в очередях можно извлечь с помощью команды Transact-SQL RECEIVE или процедуры активации, которая будет вызываться всякий раз, когда сообщение поступает в очередь. The messages in the queues can be fetched using the Transact-SQL RECEIVE command or by the activation procedure that will be called whenever the message arrives in the queue.
Создание служб Creating services
Службы базы данных создаются с помощью инструкции Transact SQL CREATE SERVICE. Database services are created by using the CREATE SERVICE Transact SQL statement. Службы могут быть связаны с очередью сообщений, созданной с помощью инструкции CREATE QUEUE: Service can be associated with the message queue create by using the CREATE QUEUE statement:
Отправка сообщений Sending messages
Сообщения отправляются во время диалога между службами с помощью инструкции Transact-SQL SEND. Messages are sent on the conversation between the services using the SEND Transact-SQL statement. Диалог — канал связи, который устанавливается между службами с помощью инструкции Transact-SQL BEGIN DIALOG . A conversation is a communication channel that is established between the services using the BEGIN DIALOG Transact-SQL statement.
Сообщение будет отправлено в ExpenssesService и помещено в dbo.ExpenseQueue . The message will be sent to the ExpenssesService and placed in dbo.ExpenseQueue . Так как процедуры активации, связанной с этой очередью, нет, сообщение будет оставаться в очереди, пока кто-то не считает его. Because there is no activation procedure associated to this queue, the message will remain in the queue until someone reads it.
Обработка сообщений Processing messages
Сообщения, помещенные в очередь, можно выбрать с помощью стандартного запроса SELECT . The messages that are placed in the queue can be selected by using a standard SELECT query. Инструкция SELECT не изменяет очередь и не удаляет сообщения. The SELECT statement will not modify the queue and remove the messages. Для чтения и извлечения сообщений из очереди можно использовать инструкции Transact-SQL RECEIVE. To read and pull the messages from the queue, you can use the RECEIVE Transact-SQL statement.
После обработки всех сообщений из очереди необходимо закрыть диалог с помощью инструкции Transact-SQL END CONVERSATION. Once you process all messages from the queue, you should close the conversation using the END CONVERSATION Transact-SQL statement.
Где найти документацию по компоненту Service Broker? Where is the documentation for Service Broker?
Справочная документация по компоненту Компонент Service Broker Service Broker входит в документацию по SQL Server SQL Server . The reference documentation for Компонент Service Broker Service Broker is included in the SQL Server SQL Server documentation. В эту справочную документацию входят следующие разделы: This reference documentation includes the following sections:
См. информацию об инструкциях CREATE, ALTER и DROP в разделе Инструкции на языке описания данных (DDL) (Transact-SQL) Data Definition Language (DDL) Statements (Transact-SQL) for CREATE, ALTER, and DROP statements
Сведения об основных понятиях компонента , а также задачах разработки и управления см. в ранее опубликованной документации Компонент Service Broker Service Broker . See the previously published documentation for Компонент Service Broker Service Broker concepts and for development and management tasks. Данная документация не воспроизводится в документации SQL Server SQL Server из-за небольшого числа изменений Компонент Service Broker Service Broker в недавних версиях SQL Server SQL Server . This documentation is not reproduced in the SQL Server SQL Server documentation due to the small number of changes in Компонент Service Broker Service Broker in recent versions of SQL Server SQL Server .
Новые возможности (компонент Service Broker) What’s new in Service Broker
Service Broker и Управляемый экземпляр SQL Azure Service broker and Azure SQL Managed Instance
Обмен сообщениями через Service Broker поддерживается только между управляемыми экземплярами SQL Azure: Cross-instance service broker message exchange is supported only between Azure SQL Managed Instances:
- CREATE ROUTE : нельзя использовать CREATE ROUTE с аргументом ADDRESS, для которого значение отличается от LOCAL или указано DNS-имя другого управляемого экземпляра SQL. CREATE ROUTE : You can’t use CREATE ROUTE with ADDRESS other than LOCAL or DNS name of another SQL Managed Instance. Должен быть указан порт 4022. Port specified must be 4022. См. статью о CREATE ROUTE. See CREATE ROUTE.
- ALTER ROUTE : нельзя использовать ALTER ROUTE с аргументом ADDRESS, для которого значение отличается от LOCAL или указано DNS-имя другого управляемого экземпляра SQL. ALTER ROUTE : You can’t use ALTER ROUTE with ADDRESS other than LOCAL or DNS name of another SQL Managed Instance. Должен быть указан порт 4022. Port specified must be 4022. См. статью об ALTER ROUTE. See See ALTER ROUTE.
Защита транспорта поддерживается, а защита обмена данными — нет: Transport security is supported, dialog security is not:
- Тип CREATE REMOTE SERVICE BINDING не поддерживается. CREATE REMOTE SERVICE BINDING is not supported.
Компонент Service Broker включен по умолчанию и его нельзя отключить. Service broker is enabled by default and cannot be disabled. Следующие параметры ALTER DATABASE не поддерживаются: The following ALTER DATABASE options are not supported:
В SQL Server 2019 (15.x) SQL Server 2019 (15.x) не были внесены значимые изменения. No significant changes were introduced in SQL Server 2019 (15.x) SQL Server 2019 (15.x) . В SQL Server 2012 (11.x) SQL Server 2012 (11.x) появились следующие изменения. The following changes were introduced in SQL Server 2012 (11.x) SQL Server 2012 (11.x) .
Сообщения могут отправляться в несколько целевых служб (многоадресная рассылка) Messages can be sent to multiple target services (multicast)
Синтаксис инструкции SEND (Transact-SQL) расширен для включения многоадресной рассылки благодаря поддержке нескольких дескрипторов диалога. The syntax of the SEND (Transact-SQL) statement has been extended to enable multicast by supporting multiple conversation handles.
Очереди предоставляют время нахождения сообщения в очереди Queues expose the message enqueued time
Очереди содержат новый столбец message_enqueue_time, в котором показано время нахождения сообщения в очереди. Queues have a new column, message_enqueue_time, that shows how long a message has been in the queue.