如何在侦听消息时阻止Azure消息会话处理程序超时?

时间:2018-04-19 14:18:08

标签: azure timeout azure-webjobs azureservicebus azure-servicebus-queues

以下是我的IMessageSessionHandler接口的同步实现。我遇到的一个问题是,当队列中没有消息时,InitializeReceiverSync方法将重复运行,直到Web作业在Azure中不合时宜地超时,从而导致失败。另一方面,如果队列中有要读取的消息,一旦读取它们,会话就会关闭并退出程序。

如果队列中没有消息,退出方法的最佳方法是什么?

    public void ReceiveMessagesFromAzure()
    {
        int i = 0;
        while (i < 4)
        {
            var QueueName = ConfigurationManager.AppSettings["QueueName"];
            var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            CancellationTokenSource cts = new CancellationTokenSource();
            InitializeReceiverSync(connectionString, QueueName, cts.Token);
            i++;
        }

    }
    public void InitializeReceiverSync(string connectionString, string queueName, CancellationToken ct)
    {
        var receiverFactory = MessagingFactory.CreateFromConnectionString(connectionString);
        ct.Register(() => receiverFactory.Close());

        var client = receiverFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock);

        client.RegisterSessionHandler(
            typeof(SessionHandler),
            new SessionHandlerOptions
            {
                MessageWaitTimeout = TimeSpan.FromSeconds(5),
                MaxConcurrentSessions = 1,
                AutoComplete = false
            });

    }

    class SessionHandler : IMessageSessionHandler
    {

        AzureRepository ar = new AzureRepository([queueName], [connectionString]);
        void IMessageSessionHandler.OnMessage(MessageSession session, BrokeredMessage message)
        {
            ar.ProcessMessage(message);
        }

        void IMessageSessionHandler.OnCloseSession(MessageSession session)
        {
            Console.WriteLine("Session closed");
            Environment.Exit(0);
        }

        void IMessageSessionHandler.OnSessionLost(Exception exception)
        {
            Console.WriteLine(exception.Message);
            Console.WriteLine("Press any key to exit");
        }
    }

0 个答案:

没有答案