Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Last active June 5, 2020 15:58
Show Gist options
  • Select an option

  • Save changhuixu/ddcb55c4d20662623c312fff4598a304 to your computer and use it in GitHub Desktop.

Select an option

Save changhuixu/ddcb55c4d20662623c312fff4598a304 to your computer and use it in GitHub Desktop.
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private ConnectionFactory _connectionFactory;
private IConnection _connection;
private IModel _channel;
private const string QueueName = "ordering.emailworker";
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
_connectionFactory = new ConnectionFactory
{
UserName = "ops1",
Password = "ops1"
};
_connection = _connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
_channel.QueueDeclarePassive(QueueName);
_channel.BasicQos(0, 1, false);
_logger.LogInformation($"Queue [{QueueName}] is waiting for messages.");
return base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// listen to the RabbitMQ messages, and send emails
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
_connection.Close();
_logger.LogInformation("RabbitMQ connection is closed.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment