Skip to content

Instantly share code, notes, and snippets.

View changhuixu's full-sized avatar
💭
Everyone has a happy ending. If you're not happy, it's not the end.

Changhui Xu changhuixu

💭
Everyone has a happy ending. If you're not happy, it's not the end.
View GitHub Profile
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime hostApplicationLifetime)
{
// ...
hostApplicationLifetime.ApplicationStarted.Register(() => { });
hostApplicationLifetime.ApplicationStopping.Register(() =>
{
var rabbitMqClient = app.ApplicationServices.GetRequiredService<IRabbitMQClient>();
rabbitMqClient.CloseConnection();
});
public void ConfigureServices(IServiceCollection services)
{
var rabbitHostName = Environment.GetEnvironmentVariable("RABBIT_HOSTNAME");
var connectionFactory = new ConnectionFactory
{
HostName = rabbitHostName ?? "localhost",
Port = 5672,
UserName = "ops0",
Password = "ops0"
};
public class RabbitMQClient : IRabbitMQClient
{
private readonly IConnection _connection;
private readonly IModel _channel;
public RabbitMQClient(IConnection connection)
{
_connection = connection;
_channel = _connection.CreateModel();
_channel.ConfirmSelect();
version: '3.8'
services:
rabbitmq:
image: rabbitmq:3-management-alpine
hostname: my-rabbit
volumes:
- ./rabbitmq/etc/definitions.json:/etc/rabbitmq/definitions.json
- ./rabbitmq/etc/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf
- ./rabbitmq/data:/var/lib/rabbitmq/mnesia/rabbit@my-rabbit
var rabbitHostName = Environment.GetEnvironmentVariable("RABBIT_HOSTNAME");
_connectionFactory = new ConnectionFactory
{
HostName = rabbitHostName ?? "localhost",
Port = 5672,
// ...
};
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-alpine AS build
WORKDIR /app
COPY ./*.csproj ./
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /out --no-restore
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-alpine AS runtime
WORKDIR /app
_connectionFactory = new ConnectionFactory
{
//...
DispatchConsumersAsync = true
};
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.ThrowIfCancellationRequested();
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.Received += async (bc, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
_logger.LogInformation($"Processing msg: '{message}'.");
try
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)
{
loopback_users.guest = false
listeners.tcp.default = 5672
management.listener.port = 15672
management.listener.ssl = false
management.load_definitions = /etc/rabbitmq/definitions.json