gpt4 book ai didi

c# - 如何将参数传递给 IEventProcessor 的实现

转载 作者:太空狗 更新时间:2023-10-29 20:50:05 25 4
gpt4 key购买 nike

我正忙于为 azure 的 EventBus 客户端实现 EventProcessorHost 客户端。

我有一个实现 IEventProcessor 的类,如下所示:

 public class MyEventProcessor : IEventProcessor
{
Stopwatch checkpointStopWatch;

//TODO: get provider id from parent class


public async Task CloseAsync(PartitionContext context, CloseReason reason)
{
Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason);
if (reason == CloseReason.Shutdown)
{
await context.CheckpointAsync();
}
}

public Task OpenAsync(PartitionContext context)
{
Debug.WriteLine("SimpleEventProcessor initialized. Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset);
eventHandler = new MyEventHandler();
this.checkpointStopWatch = new Stopwatch();
this.checkpointStopWatch.Start();
return Task.FromResult<object>(null);
}

async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
foreach (EventData eventData in messages)
{
string data = Encoding.UTF8.GetString(eventData.GetBytes());
Debug.WriteLine(data);
}
//Call checkpoint every 5 minutes, so that worker can resume processing from the 5 minutes back if it restarts.
if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
{
await context.CheckpointAsync();
this.checkpointStopWatch.Restart();
}
}
}

然后我将其称为如下:

 EventProcessorHost _eventProcessorHost = new EventProcessorHost(eventProcessorHostName, EndpointName, EventHubConsumerGroup.DefaultGroupName, ConnectionString, storageConnectionString, "messages-events");
await _eventProcessorHost.RegisterEventProcessorAsync<MyEventProcessor>();

我需要将参数传递给 EventProcessorHost 创建的 MyEventProcessor 实例。我该如何去做呢?

最佳答案

您只需要使用 RegisterEventProcessorFactoryAsync传入 factory instance 。该工厂类可以传入工厂方法中合适的任何参数,方法可能是首先将它们传递到工厂中,或者让工厂改变行为。在下面列出的代码中,您可以看到两个参数被传递到 IEventProcessor 中。 。其中一个来自工厂的参数,另一个是工厂被调用次数的计数器。

class AzureStreamProcessor : IEventProcessor
{
....
}

class AzureStreamProcessorFactory : IEventProcessorFactory
{
public AzureStreamProcessorFactory(string str)
{
this.randomString = str;
}

private string randomString;
private int numCreated = 0;
IEventProcessor IEventProcessorFactory.CreateEventProcessor(PartitionContext context)
{
return new AzureStreamProcessor(context, randomString, Interlocked.Increment(ref numCreated));
}
}

host.RegisterEventProcessorFactoryAsync(new AzureStreamProcessorFactory("a parameter"), options);

关于c# - 如何将参数传递给 IEventProcessor 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33371803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com