Is it correct to create EventHubClient for every message I send?
Creating a client directly using the EventHubClient.CreateFromConnectionString(...) will create a new tcp connection for each client.However, when creating the client using a shared MessagingFactory
var factory = MessagingFactory.CreateFromConnectionString("your_connection_string");var client = factory.CreateEventHubClient("MyEventHub");
the client will reuse the underlying tcp connection. From the docs: Create an Event Hubs client
No, It's necessary to create a new EventHubClient using the MessageFactory only the first time. If I create a Client for every message I send, then a new connection is created and the old one remain opened (checked using netstat) resulting in a lot of "ESTABILISHED" connections.
Using a single client created for the first message, then recycling the client for the other messages, if the internet connection is lost then comes back, the tcp connection is automatically re-created.
Here is an example of a client creation using factory:
var endpointUri = ServiceBusEnvironment.CreateServiceUri("sb", eventHubNamespace, string.Empty); MessagingFactory factory = MessagingFactory.Create(endpointUri, new MessagingFactorySettings { TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasToken), TransportType = TransportType.Amqp }); factory.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), 3); client = factory.CreateEventHubClient(eventHubName);