Implementing a Message Consumer in dotnet Core on Linux container

6/13/2019

I’m looking to implement a service that will be deployed on a Linux kubernetes cluster. It’s going to consume and process messages from a queue.

My question is, what is the recommended and conventional way of implementing a worker in dotnet core today? A background task in an ASPNET application seems overkill as I have no requirement for serving web requests. A bit of research leads me to think a console app building an IHost and a custom IHostedService would do the job. I’m surprised at the absence of examples for this scenario though which got me wondering if I’m missing a more standard way to implement this?

-- Sio
.net-core
architecture
docker
kubernetes
linux

1 Answer

6/14/2019

Using a 'simple' console app, by adding Console.ReadLine() at the last code line will obviously not work as there's no input stream while running in K8s.

The recommended way to implement this is using a Host Builder.

WebHost is for web applications, as you mentioned, but there's a generic host builder for all other types of applications that generally do not required web capabilities.

Although at first it might seems a bit of an 'overkill' - it really is not. When planning on running on Kubernetes, you must consider other paths other than the happy one. For example, allowing K8s signalling you to terminal (handling SIGTERM) in case of scale down event on that deployment, or node draining - for graceful shutdown - which is supported out-of-the-box when using the HostBuilder. In addition will you be able to enjoy other built-in features such as auto-reload of settings from files (which works beautifully when mounting ConfigMap to a file)

Documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2

Sample project: https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/2.x/GenericHostSample

Good luck.

-- Ofir Makmal
Source: StackOverflow