我在目标队列中的消息在 SQL Server Service Broker 中不可读

My message in target queue is not readable in SQL Server Service Broker

我正在使用 Service broker 连接我系统中的其他域,正如您在此处看到的那样,我向目标服务发送了一条消息,如下所示:

_ctx.Database.ExecuteSqlCommand(@"Declare @ConversationHandle uniqueidentifier

Begin Transaction
Begin Dialog @ConversationHandle
 From Service SenderService
 To Service 'ReceiverService'
 On Contract SampleContract
 WITH Encryption=off;
SEND 
      ON CONVERSATION @ConversationHandle
      Message Type SenderMessageType
  ('<Reception>Add</Reception><OrganizationId>2</OrganizationId>') Commit");

另一方面,我启用了 SP 来获取这样的消息:

ALTER PROCEDURE [dbo].[usp_ProcessTargetQueue] as
BEGIN
Declare @ConversationHandle as uniqueidentifier
Declare @MessageBody as nvarchar(max)
Declare @MessageType as sysname
declare @MessageBodyXML as xml


    WHILE (1=1)
    BEGIN

        BEGIN TRANSACTION;
        WAITFOR (
           RECEIVE top (1)
      @MessageType = message_type_name,
      @ConversationHandle = conversation_handle,
    @MessageBody = message_body
FROM TargetQueue

        ), TIMEOUT 5000;

       IF (@@ROWCOUNT = 0)
        BEGIN
              ROLLBACK TRANSACTION;
              BREAK;
        END
if @MessageType = 'SenderMessageType'
      BEGIN
            SEND 
                  ON CONVERSATION @ConversationHandle
                  Message Type ReceiverMessageType
                  ('Message is received')
            END Conversation @ConversationHandle

        set @MessageBodyXML=    (select cast(@MessageBody as xml)  )

      insert into s (s1) select CONVERT(nvarchar(max), @MessageBodyXML)

   END


        COMMIT TRANSACTION;




     END  

    END

如您所见,我将 message_body 插入 s1 table,但是当我检查 table 时,我看不到消息。

此代码将一个 varchar 值插入二进制 message_body:

SEND 
      ON CONVERSATION @ConversationHandle
      Message Type SenderMessageType
  ('<Reception>Add</Reception><OrganizationId>2</OrganizationId>') Commit");

但此代码将二进制值转换为 nvarchar,因此该值被误解:

insert into s (s1) select CONVERT(nvarchar(max), @MessageBodyXML)

解决此问题的一种方法是指定 N 前缀,以便 xml 字符串是 Unicode 文字:

SEND 
      ON CONVERSATION @ConversationHandle
      Message Type SenderMessageType
  (N'<Reception>Add</Reception><OrganizationId>2</OrganizationId>') Commit");