I am having ManagedMqttClient to establish connection to Solace.
public async Task Connect()
{
_mqttClient = new MqttFactory().CreateManagedMqttClient();
_mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId(_options.ClientId)
.WithTcpServer(_options.Host, _options.Port);
ManagedMqttClientOptions managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
.WithClientOptions(_mqttClientOptions)
.Build();
await _mqttClient.StartAsync(managedMqttClientOptions);
_mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
_logger.LogDebug("MQTT connection is made; Result code: {ConnectResult}", e.ConnectResult.ResultCode));
_mqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(e =>
_logger.LogError("MQTT connection is failed; Exception: {Exception}", e.Exception.Demystify()));
_mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(e =>
_logger.LogDebug("MQTT connection is end; Reason: {Reason}", e.Reason));
_mqttClient.UseApplicationMessageReceivedHandler(MessageReceivedHandler);
}
It works great for one instance of the service which is MQTT client. However, when up another instance of the service in parallel I am facing with reconnection issue. It making connection and disconnection on both service every second.
Is there some way to use MQTTnet and scale my services without such problem. Thank you in advance!
MQTTnet packages:
<PackageReference Include="MQTTnet" Version="3.1.2" />
<PackageReference Include="MQTTnet.Extensions.ManagedClient" Version="3.1.2" />
It's not the problem of MQTTnet Managed Client. Digging down about MQTT I find that
If you attempt to connect to an MQTT broker with the same name as an existing client then the existing client connection is dropped. Because most MQTT clients will attempt to reconnect following a disconnect this can result in a loop of disconnect and connect.
So Solace dropping one client and replace it with another. It could be fixed with Shared Subscription feature. In my case Solace supports it, and also MQTTnet supports such feature. All necessary is to use $share/group in your topic to subscribe and create clients with different ids. For more information could check MQTTnet Load Balancing.