如何注册以接收只有特定会话 ID 的服务总线会话消息?

How to register to receive service bus session messages that only have a particular session id?

  1. 我正在使用 .net core 3.1 和 Microsoft.Azure.ServiceBus(版本 5.1.3)。
  2. 我有一个服务总线主题和一个只能处理会话消息的订阅。

主题客户端可以发送 3 条带有会话 ID(例如 ABCD)的消息,然后发送另外 4 条带有会话 ID (XYZ) 的消息。编写订阅客户端以接收具有相关会话 ID 的所有 7 条消息非常容易。但是,我希望能够仅接收会话 ID 为 XYZ 的消息(并且不关心会话 ID 为 ABCD 的消息,甚至不想接收它们)。

以下用于接收具有所有会话 ID 的所有消息的示例代码按预期工作:

static async Task Main(string[] args)
{
    try
    {
        byte[] messageBody = System.Text.Encoding.Unicode.GetBytes("Hello, world!");
        ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString);

        SubscriptionClient client = new SubscriptionClient(builder, subscriptionName, ReceiveMode.PeekLock);

        var sessionHandler = new SessionHandlerOptions(ExceptionHandler);
        sessionHandler.AutoComplete = true;
        client.RegisterSessionHandler(SessionMessageHandler, sessionHandler);

        Console.WriteLine("Press any key to exit!");
        Console.ReadKey();

        await client.CloseAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }        
}

static Task SessionMessageHandler(IMessageSession session, Message message, CancellationToken cancellationToken)
{
    var bodyText = System.Text.Encoding.Unicode.GetString(message.Body);
    Console.WriteLine($"Session id: {message.SessionId}; Body: {bodyText}");
    return Task.CompletedTask;
}

static Task ExceptionHandler(ExceptionReceivedEventArgs args)
{
    var context = args.ExceptionReceivedContext;
    Console.WriteLine($"Exception context: {context.Action}, {context.ClientId}, {context.Endpoint}, {context.EntityPath}");
    Console.WriteLine($"Exception: {args.Exception}");
    return Task.CompletedTask;
}

问题:

  1. 如何更改上面的代码,以便我只接收会话 ID 为 XYZ 的消息(而不接收会话 ID 为 ABCD 的消息)?
  2. 如果上面的代码无法实现,有没有其他方法可以实现我想要的(使用相同的库)?如果是,请举例说明。

上面的代码使用了一个会话处理程序,该处理程序旨在处理多个会话,而不仅仅是一个会话。如果您只想处理具有特定 ID 的单个会话,则需要使用 SessionClient 及其接受会话 ID 作为参数的 AcceptMessageSessionAsync(String) method

根据 Sean 的建议,我将代码修改为以下内容并且可以正常工作。谢谢肖恩。

    static async Task Main(string[] args)
    {
        try
        {
            Console.WriteLine("Enter session id to listen on ...");
            var sessionId = Console.ReadLine();
            if (sessionId == string.Empty)
            {
                sessionId = "12345";
            }
            Console.WriteLine($"Reading messages with session id: {sessionId}");

            var sessionClient = new SessionClient(connectionStringWithoutEntityPath, subscriberPath, ReceiveMode.PeekLock);

            var messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId);

            if (messageSession != null)
            {
                while(true)
                {
                    Message message = await messageSession.ReceiveAsync();

                    if (message != null)
                    {
                        var bodyText = System.Text.Encoding.Unicode.GetString(message.Body);
                        Console.WriteLine($"Session id: {message.SessionId}; Body: {bodyText}");
                        await messageSession.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    else
                    {
                        Console.WriteLine("Press Enter to keep reading. Otherwise press any other key to exit.");
                        if (Console.ReadLine() != string.Empty)
                        {
                            break;
                        }
                    }
                }
            }

            await sessionClient.CloseAsync();
            Console.WriteLine("Press any key to exit!");
            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }        
    }