Service Broker实现发布-订阅(Publish-Subscribe)框架(3)

Service Broker实现发布-订阅(Publish-Subscribe)框架(3)


这一主题前面相关的文章如下:
Service Broker实现发布-订阅(Publish-Subscribe)框架(1)
Service Broker实现发布-订阅(Publish-Subscribe)框架(2)


发布信息Publishing Information
这一节演示订阅者通过订阅从PublisherService服务接收信息,已经AuthorService如何发送新的article消息到PublisherService服务进行分发。在订阅者可以从PublisherService接收新的article消息之前,它必须请求一个订阅。可以通过发送一个 [http://ssb.csharp.at/SSB_Book/c10/SubscribeMessage] 消息来实现,代码如下:
 
订阅方请求订阅脚本:
DECLARE @ch UNIQUEIDENTIFIER;
BEGIN DIALOG CONVERSATION @ch
FROM SERVICE [SubscriberService1]
TO SERVICE 'PublisherService'
ON CONTRACT [http://ssb.csharp.at/SSB_Book/c10/SubscribeContract]
WITH ENCRYPTION = OFF;
SEND ON CONVERSATION @ch
MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c10/SubscribeMessage]
(
N'<?xml version="1.0"?>
<Request xmlns="http://ssb.csharp.at/SSB_Book/c10/PublishSubscribe">
<Subject>Subject1</Subject>
</Request>'
);
GO
 
在上述脚本中,你必须在发送的消息中指定消息主题,随后会根据主题从PublisherService 中获取发布数据。在订阅者一设置好订阅,AuthorService就可以发送article消息给PublisherService进行分发。示例代码如下:
 
[AuthorService] 发送PublishMessage消息:
DECLARE @ch UNIQUEIDENTIFIER;
BEGIN DIALOG CONVERSATION @ch
FROM SERVICE [AuthorService]
TO SERVICE 'PublisherService'
ON CONTRACT [http://ssb.csharp.at/SSB_Book/c10/PublishContract]
WITH ENCRYPTION = OFF;
SEND ON CONVERSATION @ch
MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c10/PublishMessage]
(
N'<?xml version="1.0"?>
<Publish xmlns="http://ssb.csharp.at/SSB_Book/c10/PublishSubscribe">
<Subject>Subject1</Subject>
</Publish>'
);
 
AuthorService必须指定随后的article消息属于哪一主题,它通过发送[http://ssb.csharp.at/SSB_Book/c10/PublishMessage] 消息类型,通知PublisherService 记录相应的发布记录。最后,AuthorService 发送属于前面指定主题的、不同的article消息。
 
发送特定主题的article消息:
SEND ON CONVERSATION @ch
MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c10/ArticleMessage]
(
N'This is an article on Subject1'
);
SEND ON CONVERSATION @ch
MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c10/ArticleMessage]
(
N'And this is another article on Subject1'
);
GO
 
在AuthorService 一发送article消息到PublisherService,这些消息将通过sp_PublisherService存储过程自动转发给订阅者。现在,你可以查询订阅者服务对应的队列,⑾址⑺偷腶rticle消息成功转发过来了。
 
备注:因为Service Broker内在的异步处理特性,在你查看SubscriberQueue1和SubscriberQueue2队列之前,你需要等待几秒钟,直到这些消息已经处理完成。
 
EntLib.com译者注:本文翻译Apress出版《Pro SQL Server 2005 Service Broker》的其中一个章节。现已翻译完成,欢迎交流、分享。谢谢!


posted on 2008-06-24 22:37  EntLib  阅读(1898)  评论(0编辑  收藏  举报