MQTT - Basic
This sample implements the simplest possible producer and consumer.
What This Sample Shows
- Connecting Silverback to an MQTT broker with
AddMqttand moving the clients configuration to anIBrokerClientsConfigurator. - Producing the
SampleMessageto thesamples/basictopic with at-least-once QoS and the retain flag, logging a warning when no subscriber matches. - 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.Producer/.
dotnet run --project ./samples/MQTT/Basic.Consumer/.
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.Producer;
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.Producer
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.Consumer;
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.Consumer