Steeltoe Documentation
  • Why Steeltoe
    Overview Microservices Cloud Web Applications Event Driven
  • Get Started
    Steeltoe Initializr Guides Documentation API Browser Blog
  • Projects
    Steeltoe Application Configuration Steeltoe Circuit Breakers Steeltoe Dynamic Logging Steeltoe Management Steeltoe Messaging Steeltoe Network File Shares Steeltoe Security Steeltoe Service Connectors Steeltoe Service Discovery Steeltoe Stream
  • Support
  • Community
Search Results for

    Table of Contents
    . . .

    RabbitMQ Messaging

    This tutorial takes you through setting up 2 .NET Core applications that interact through RabbitMQ.

    Note

    For more detailed examples, please refer to the Messaging solution in the Steeltoe Samples Repository.

    First, start a RabbitMQ instance. Using the Steeltoe dockerfile, start a local instance of RabbitMQ

    docker run --publish 5672:5672 steeltoeoss/rabbitmq
    

    Next create a .NET Core WebAPI that will ensure the queue is created and write messages to it.

    1. Create a new ASP.NET Core WebAPI app with the Steeltoe Initializr Steeltoe Initialzr - RabbitMQ

    2. Name the project "WriteToRabbitMQ"

    3. Add RabbitMQ Messaging Dependency

    4. Click Generate Project to download a zip containing the new project

    5. Extract the zipped project and open in your IDE of choice

    6. Open the package manager console Visual Studio - Open Package Manager

    7. Install NuGet distributed packages

      Install-Package -Id Steeltoe.Messaging.RabbitMQ
      
    8. Ensure RabbitMQHost appears in Program.cs

      See RabbitMQHost documentation to further understand what is happening behind the scenes

      public static IHostBuilder CreateHostBuilder(string[] args) =>
           RabbitMQHost.CreateDefaultBuilder()
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.UseStartup<Startup>();
               });
      
    9. Add rabbit messaging configurations to Startup.cs

      using Steeltoe.Messaging.RabbitMQ.Config;
      using Steeltoe.Messaging.RabbitMQ.Extensions;
      
      public class Startup {
        public const string RECEIVE_AND_CONVERT_QUEUE = "steeltoe_message_queue";
      
        public void ConfigureServices(IServiceCollection services){
      
          // Add a queue to the message container that the rabbit admin will discover and declare at startup
          services.AddRabbitQueue(new Queue(RECEIVE_AND_CONVERT_QUEUE));
        }
      }
      
    10. Create a new controller class Controllers\WriteMessageQueueController.cs

      using Microsoft.Extensions.Logging;
      using Steeltoe.Messaging.RabbitMQ.Core;
      
      [ApiController]
      [Route("[controller]")]
      public class WriteMessageQueueController : ControllerBase {
        public const string RECEIVE_AND_CONVERT_QUEUE = "steeltoe_message_queue";
        private readonly ILogger<WriteMessageQueueController> _logger;
        private readonly RabbitTemplate _rabbitTemplate;
        private readonly RabbitAdmin _rabbitAdmin;
      
        public WriteMessageQueueController(ILogger<WriteMessageQueueController> logger, RabbitTemplate rabbitTemplate, RabbitAdmin rabbitAdmin) {
        _logger = logger;
        _rabbitTemplate = rabbitTemplate;
        _rabbitAdmin = rabbitAdmin;
        }
      
        [HttpGet()]
        public ActionResult<string> Index() {
          var msg = "Hi there from over here.";
      
          _rabbitTemplate.ConvertAndSend(RECEIVE_AND_CONVERT_QUEUE, msg);
      
          _logger.LogInformation($"Sending message '{msg}' to queue '{RECEIVE_AND_CONVERT_QUEUE}'");
      
          return "Message sent to queue.";
        }
      }
      
    11. Validate the port number the app will be served on, in Properties\launchSettings.json

      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:8080",
          "sslPort": 0
        }
      }
      

    Run the application (you won't be interacting directly with it, we just need it running in the background)

    • .NET cli
    • Visual Studio
    dotnet run<PATH_TO>\WriteToRabbitMQ.csproj
    
    1. Choose the top Debug menu, then choose Start Debugging (F5). This should bring up a browser with the app running
    Note

    Minimize windows and leave the application running as you continue on to the next step.

    Now create a .NET Core WebAPI that will monitor the queue and output anything received.

    1. Create a new ASP.NET Core WebAPI app with the Steeltoe Initializr Steeltoe Initialzr - No Dependencies

    2. Name the project "MonitorRabbitMQ"

    3. No need to add any dependencies

    4. Click Generate Project to download a zip containing the new project

    5. Extract the zipped project and open in your IDE of choice

      Tip

      Open the second app in a different Visual Studio instance.

    6. Open the package manager console Visual Studio - Open Package Manager

    7. Install NuGet distributed packages

      Install-Package -Id Steeltoe.Messaging.RabbitMQ
      
    8. Create a new service class named RabbitListenerService.cs

      using Microsoft.Extensions.Logging;
      using Steeltoe.Messaging.RabbitMQ.Attributes;
      
      public class RabbitListenerService {
        public const string RECEIVE_AND_CONVERT_QUEUE = "steeltoe_message_queue";
        private ILogger _logger;
      
        public RabbitListenerService(ILogger<RabbitListenerService> logger) {
          _logger = logger;
        }
      
        [RabbitListener(RECEIVE_AND_CONVERT_QUEUE)]
        public void ListenForAMessage(string msg) {
          _logger.LogInformation($"Received the message '{msg}' from the queue.");
        }
      }
      
    9. Add rabbit messaging configurations to Startup.cs

      using Steeltoe.Messaging.RabbitMQ.Extensions;
      
      public class Startup {
        public const string RECEIVE_AND_CONVERT_QUEUE = "steeltoe_message_queue";
      
        public void ConfigureServices(IServiceCollection services){
          // Add steeltoe rabbit services
          services.AddRabbitServices();
      
          // Add singleton that will process incoming messages
          services.AddSingleton<RabbitListenerService>();
      
          // Tell steeltoe about singleton so it can wire up queues with methods to process queues
          services.AddRabbitListeners<RabbitListenerService>();
        }
      }
      
    10. Validate the port number the app will be served on, in Properties\launchSettings.json

      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:8081",
          "sslPort": 0
        }
      }
      

    Run the application

    • .NET cli
    • Visual Studio
    dotnet run<PATH_TO>\WriteToRabbitMQ.csproj
    
    1. Choose the top Debug menu, then choose Start Debugging (F5). This should bring up a browser with the app running
    Note

    If a browser window popped up, minimize it.

    Validate the apps are working properly and the message queue is in use.

    1. View the WriteToRabbitMQ project message logs and verify there is a message stating it is "Sending message to queue". If you don't see the message refresh the endpoint https://localhost:8080/WriteMessageQueue to have a new message written. Visual Studio - Debug Output
    2. View the MonitorRabbitMQ project message logs and verify there is a message stating it "Received the message from the queue". Visual Studio - Debug Output Message Received
    X
    • Edit this page