0
votes

I am developing a long-running program that sends data periodically to an Azure IoT Hub. I am using the com.microsoft.azure.sdk.iot.device/DeviceClient Java class to accomplish this.

It's basically working, which is nice, but I have some questions about the lifetime of the DeviceClient instance.

Should I instantiate exactly one DeviceClient instance at program startup, and then repeatedly call .sendEventAsync any time I have data to send? Or should I instantiate a new DeviceClient instance fresh from the connection string each time I want to send data? Or something in-between (e.g., send no more than 100 messages with a given DeviceClient instance, or let no DeviceClient instance live more than 72 hours)?

As I said, it's basically working, we've successfully sent many many events, but we have also seen some funny behavior. For example, after a few weeks the client silently stops sending (oof), or after some time the client claims send SUCCESS_OK, but the events don't arrive in the IoT hub for several hours (up to 16 (!)). I can definitely imagine these occurrences steming from my misuse of the library, so any hints about how to use it correctly would be much appreciated.

Thanks in advance for your time and consideration.

1

1 Answers

2
votes

You should only have one long-living DeviceClient instance. Especially if you are using MQTT or AMQP as transport protocol, the DeviceClient will open the connection - and keep it open. Over that open connection it will send the messages. And also the for cloud-to-device messages / twin updates, the same channel is used.

Also, the client usually handles any connection-retry logic so you don't have to deal with that manually.