简体   繁体   English

发送异步天蓝色事件中心数据方法

[英]send async azure event hub data method

In my api (c#), i'm currently answering lots of request (15-20 in a second).在我的 api (c#) 中,我目前正在回答大量请求(每秒 15-20 个)。 Now i want to send the data to event hub for some purposes.现在我想出于某些目的将数据发送到事件中心。 But i dont want to delay the user for sending data to azure event hub.但我不想延迟用户将数据发送到 azure 事件中心。 So i need to make async request to event hub beacuse while my app sending data to azure i dont want to get user waited for my answer.所以我需要向事件中心发出异步请求,因为当我的应用程序向 azure 发送数据时,我不想让用户等待我的回答。 I need to send response as quick as possible, azure may last 2-3 second.我需要尽快发送响应,azure 可能会持续 2-3 秒。

How can i success that?我怎么能成功呢? I ve done smth but didnt get what i want.我做了一些事情,但没有得到我想要的。 My code:我的代码:

public static async Task<string> SendEvents(List<object> messages)
{
    string eventHubName = "rcmds";

    var connectionString = GetServiceBusConnectionString();

    CreateEventHub(eventHubName, connectionString);

    var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);

    try
    {
        List<Task> tasks = new List<Task>();

        for (int i = 0; i < messages.Count; i++)
        {
            var serializedMessage = JsonConvert.SerializeObject(messages[i]);

            EventData data = new EventData(Encoding.UTF8.GetBytes(serializedMessage));

            // Mesajları Event Hub a yolla
            tasks.Add(eventHubClient.SendAsync(data));
        }

        Task.WaitAll(tasks.ToArray());
        System.Threading.Thread.Sleep(7000);
    }
    catch (Exception ex)
    {
        new ExceptionHandler(ex, "Event Hub Library Sender - SendEvents");
    }
    finally
    {
        eventHubClient.CloseAsync().Wait();
    }
    return "";
}

and i call this method like:我把这个方法称为:

 static async void method()


 {
            List<object> list = new List<object>();
            list.Add("dogrudur");
            await Utilities.EventHub.Sender.SendEvents(list);
        }

As you can see, there is "thread.sleed" code but i waited 7 seconds :/如您所见,有“thread.sleed”代码,但我等了 7 秒:/

I think you need to learn more about how to really use async/await in a good manner.我认为您需要更多地了解如何真正以良好的方式使用 async/await。 You are mixing async code with blocking code.您正在将异步代码与阻塞代码混合在一起。

The correct code should be something like this:正确的代码应该是这样的:

public static async Task<string> SendEvents(List<object> messages)
{
    string eventHubName = "rcmds";

    var connectionString = GetServiceBusConnectionString();

    CreateEventHub(eventHubName, connectionString);

    var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);

    try
    {
        List<Task> tasks = new List<Task>();

        for (int i = 0; i < messages.Count; i++)
        {
            var serializedMessage = JsonConvert.SerializeObject(messages[i]);

            EventData data = new EventData(Encoding.UTF8.GetBytes(serializedMessage));

            // Mesajları Event Hub a yolla
            tasks.Add(eventHubClient.SendAsync(data));
        }

        await Task.WhenAll(tasks.ToArray());
        System.Threading.Thread.Sleep(7000);
    }
    catch (Exception ex)
    {
        new ExceptionHandler(ex, "Event Hub Library Sender - SendEvents");
    }
    finally
    {
        await eventHubClient.CloseAsync();
    }

    return "";
}

The calling code should be:调用代码应该是:

static async Task method()
 {
        List<object> list = new List<object>();
        list.Add("dogrudur");
        await Utilities.EventHub.Sender.SendEvents(list);
    }

Now, back to the question.现在,回到问题。 The current code waits untill all messages are send to the event hub and than sleeps for 7 seconds.当前代码等待直到所有消息都发送到事件中心,然后休眠 7 秒。 In you calling method you await the SendEvents method so of course your application will take 7 seconds + the time required to send the data to the event hub.在您调用方法时,您等待SendEvents方法,因此您的应用程序当然需要 7 秒 + 将数据发送到事件中心所需的时间。

What you could do is implement some kind of fire-and-forget mechanism.你可以做的是实现某种即发即忘的机制。 Remove the Thread.Sleep in the code and modify the calling method like this:去掉代码中的Thread.Sleep ,修改调用方法如下:

static void method()
{
    List<object> list = new List<object>();
    list.Add("dogrudur");
    Utilities.EventHub.Sender.SendEvents(list);
}

The method will now no longer wait before continuing, but in return you will never know when the event sending is completed.该方法现在将不再在继续之前等待,但作为回报,您将永远不会知道事件发送何时完成。 In general fire and forget methods should be avoided.一般来说,应该避免“即发即忘”的方法。

Another important step you can take to improve the performance is to send the events in batches.您可以采取的另一个提高性能的重要步骤是批量发送事件。 Currently each event is send using eventHubClient.SendAsync but there is also a eventHubClient.SendBatchAsync method ( https://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.eventhubclient.sendbatchasync.aspx ) so instead of sending a lot of small messages you can send fewer bigger messages than contain more than one event.目前每个事件都是使用eventHubClient.SendAsync发送的,但也有一个eventHubClient.SendBatchAsync方法( https://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.eventhubclient.sendbatchasync.aspx )所以而不是发送大量小消息与包含多个事件相比,您可以发送更少的大消息。 Be aware that there is a maximum message size though.请注意,尽管存在最大消息大小。

For an example implementation of sending event using a batch see the method private async Task SendAutoSizedBatchAsync(IEnumerable collection) in this file https://github.com/DeHeerSoftware/SemanticLogging.EventHub/blob/master/SemanticLogging.EventHub/EventHubAmqpSink.cs有关使用批处理发送事件的示例实现,请参阅此文件中的private async Task SendAutoSizedBatchAsync(IEnumerable collection) https://github.com/DeHeerSoftware/SemanticLogging.EventHub/blob/master/SemanticLogging.EventHub/EventHubAmqpSink.cs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM