Azure WebJobs:具有不同批处理大小的队列触发器

时间:2018-10-03 14:43:00

标签: c# asp.net azure azure-webjobs azure-queues

我在Azure上有一个WebJob,可同时处理来自多个队列的消息:

public async static Task ProcessQueueMessage1([QueueTrigger("queue1")] string message)
    {


        switch (message.Substring(message.Length - 3, 3))
        {
            case "tze":
                await Parser.Process1(message);
                break;
            default:
                break;
        }
    }


    public async static Task ProcessQueueMessage2([QueueTrigger("queue2")] string message)
    {


        switch (message.Substring(message.Length - 3, 3))
        {
            case "tzr":
                await Parser.Process2(message);
                break;
            default:
                break;
        }
    }

然后是MAIN

static void Main()
    {

        JobHostConfiguration config = new JobHostConfiguration();
        config.Queues.BatchSize = 3;
        config.Queues.MaxDequeueCount = 1;
        var host = new JobHost(config);
        host.RunAndBlock();

    }

此处:message.Substring(message.Length - 3, 3)仅检查文件的扩展名。

我的问题是,我如何继续使queue1的批处理大小不同于queue2,我可以使第二个Jobhost具有不同的配置并具有host.RunAndBlock()host2.RunAndBlock()吗?我将如何指定作业主机应该在哪个队列中工作?

我也尝试过Groupqueue触发器,但是不幸的是它们使用字符串,在我的情况下,我实际上无法将列表传递到队列。 :(

我非常感谢您提供帮助或解决此问题的任何建议。

1 个答案:

答案 0 :(得分:2)

为了解决这个问题,您需要提供IQueueProcessorFactory的自定义实现。您只需要一个JobHost。

有一个有关如何here.的示例

    static void Main()
    {

        //Configure JobHost
        var config = new JobHostConfiguration();
        config.Queues.BatchSize = 32;
        config.Queues.MaxDequeueCount = 6;
        // Create a custom configuration
        // If you're using DI you should get this from the kernel
        config.Queues.QueueProcessorFactory = new CustomQueueProcessorFactory();

        //Pass configuration to JobJost
        var host = new JobHost(config);
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }

CustomQueueProcessorFactory 中,您可以基于队列名称插入自定义配置。

public class CustomQueueProcessorFactory : IQueueProcessorFactory
{
    public QueueProcessor Create(QueueProcessorFactoryContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        if (context.Queue.Name == "queuename1")
        {
            context.MaxDequeueCount = 10;
        }
        else if (context.Queue.Name == "queuename2")
        {
            context.MaxDequeueCount = 10;
            context.BatchSize = 1;
        }

        return new QueueProcessor(context);
    }
}

希望这会有所帮助。