MQTT - Basic (MQTT v3)
This sample implements the simplest possible producer and consumer, but using MQTT protocol version 3.
What This Sample Shows
- Selecting the MQTT protocol version 3.1.0 with
UseProtocolVersion(MqttProtocolVersion.V310). - Producing the
SampleMessageto thesamples/basictopic with at-least-once QoS and the retain flag. - Consuming the same topic with at-least-once QoS, skipping the messages that fail to be processed.
- Configuring a last will message (
TestamentMessage) that is sent to thesamples/testamentstopic if the consumer disconnects ungracefully.
How to Run
Start the infrastructure as described in Samples, then run the two applications from the repository root.
dotnet run --project ./samples/MQTT/Basic.ProducerV3/.
dotnet run --project ./samples/MQTT/Basic.ConsumerV3/.
Observe the console output while the messages are produced and consumed.
Common
The message being exchanged is defined in a common project.
namespace Silverback.Samples.Mqtt.Basic.Common;
public class SampleMessage
{
public int Number { get; set; }
}
Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/MQTT/Basic.Common
Producer
The producer uses a hosted service to publish some messages in the background.
using Microsoft.Extensions.DependencyInjection;
using Silverback.Configuration;
using Silverback.Messaging.Configuration;
namespace Silverback.Samples.Mqtt.Basic.ProducerV3;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Enable Silverback
services.AddSilverback()
// Use Apache Mqtt as message broker
.WithConnectionToMessageBroker(
options => options
.AddMqtt())
// Delegate the broker clients configuration to a separate class
.AddBrokerClientsConfigurator<BrokerClientsConfigurator>();
// Add the hosted service that produces the random sample messages
services.AddHostedService<ProducerBackgroundService>();
}
public void Configure()
{
}
}
Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/MQTT/Basic.ProducerV3
Consumer
The consumer processes the messages and outputs their value to the standard output.
using Microsoft.Extensions.DependencyInjection;
using Silverback.Configuration;
using Silverback.Messaging.Configuration;
namespace Silverback.Samples.Mqtt.Basic.ConsumerV3;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Enable Silverback
services.AddSilverback()
// Use Apache Mqtt as message broker
.WithConnectionToMessageBroker(
options => options
.AddMqtt())
// Delegate the broker clients configuration to a separate class
.AddBrokerClientsConfigurator<BrokerClientsConfigurator>()
// Register the subscribers
.AddSingletonSubscriber<SampleMessageSubscriber>();
}
public void Configure()
{
}
}
Full source code: https://github.com/BEagle1984/silverback/tree/main/samples/MQTT/Basic.ConsumerV3