Enterprise Application: Creating Message Broker using C# (.NET Core), Java (Spring Boot), and Golang

Estimated read time 4 min read

Creating a message broker involves setting up a system that enables communication between different components or services using messages. Below, I’ll provide you with a simple example of how to create a message broker using C# (.NET Core), Java (Spring Boot), and Golang. I’ll use RabbitMQ as the message broker in these examples, but you can substitute it with other options like Apache Kafka or ActiveMQ based on your requirements.

C# (.NET Core) Message Broker with RabbitMQ:

  1. Install the RabbitMQ.Client NuGet package:
   dotnet add package RabbitMQ.Client
  1. Create a publisher:
   using System;
   using RabbitMQ.Client;

   class Program
   {
       static void Main()
       {
           var factory = new ConnectionFactory() { HostName = "localhost" };
           using (var connection = factory.CreateConnection())
           using (var channel = connection.CreateModel())
           {
               channel.QueueDeclare(queue: "my_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);

               string message = "Hello, RabbitMQ!";
               var body = System.Text.Encoding.UTF8.GetBytes(message);

               channel.BasicPublish(exchange: "", routingKey: "my_queue", basicProperties: null, body: body);
               Console.WriteLine($"Sent: {message}");
           }
       }
   }
  1. Create a consumer:
   using System;
   using RabbitMQ.Client;
   using RabbitMQ.Client.Events;

   class Program
   {
       static void Main()
       {
           var factory = new ConnectionFactory() { HostName = "localhost" };
           using (var connection = factory.CreateConnection())
           using (var channel = connection.CreateModel())
           {
               channel.QueueDeclare(queue: "my_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);

               var consumer = new EventingBasicConsumer(channel);
               consumer.Received += (model, ea) =>
               {
                   var body = ea.Body.ToArray();
                   var message = System.Text.Encoding.UTF8.GetString(body);
                   Console.WriteLine($"Received: {message}");
               };

               channel.BasicConsume(queue: "my_queue", autoAck: true, consumer: consumer);

               Console.WriteLine("Press [Enter] to exit.");
               Console.ReadLine();
           }
       }
   }

Java (Spring Boot) Message Broker with RabbitMQ:

  1. Add the Spring AMQP and RabbitMQ dependencies:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-amqp</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter</artifactId>
   </dependency>
  1. Create a publisher:
   import org.springframework.amqp.core.Queue;
   import org.springframework.amqp.rabbit.core.RabbitTemplate;
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.boot.CommandLineRunner;
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;

   @SpringBootApplication
   public class Publisher implements CommandLineRunner {

       @Autowired
       private RabbitTemplate rabbitTemplate;

       @Autowired
       private Queue queue;

       public static void main(String[] args) {
           SpringApplication.run(Publisher.class, args);
       }

       @Override
       public void run(String... args) {
           String message = "Hello, RabbitMQ!";
           rabbitTemplate.convertAndSend(queue.getName(), message);
           System.out.println("Sent: " + message);
       }
   }
  1. Create a consumer:
   import org.springframework.amqp.rabbit.annotation.RabbitListener;
   import org.springframework.stereotype.Component;

   @Component
   public class Consumer {

       @RabbitListener(queues = "my_queue")
       public void receiveMessage(String message) {
           System.out.println("Received: " + message);
       }
   }

Golang Message Broker with RabbitMQ:

  1. Install the streadway/amqp package:
   go get github.com/streadway/amqp
  1. Create a publisher:
   package main

   import (
       "fmt"
       "log"
       "github.com/streadway/amqp"
   )

   func main() {
       connection, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
       if err != nil {
           log.Fatal(err)
       }
       defer connection.Close()

       channel, err := connection.Channel()
       if err != nil {
           log.Fatal(err)
       }
       defer channel.Close()

       queueName := "my_queue"
       message := "Hello, RabbitMQ!"

       _, err = channel.QueueDeclare(queueName, false, false, false, false, nil)
       if err != nil {
           log.Fatal(err)
       }

       err = channel.Publish("", queueName, false, false, amqp.Publishing{
           ContentType: "text/plain",
           Body:        []byte(message),
       })
       if err != nil {
           log.Fatal(err)
       }

       fmt.Printf("Sent: %s\n", message)
   }
  1. Create a consumer:
   package main

   import (
       "fmt"
       "log"
       "github.com/streadway/amqp"
   )

   func main() {
       connection, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
       if err != nil {
           log.Fatal(err)
       }
       defer connection.Close()

       channel, err := connection.Channel()
       if err != nil {
           log.Fatal(err)
       }
       defer channel.Close()

       queueName := "my_queue"

       messages, err := channel.Consume(queueName, "", true, false, false, false, nil)
       if err != nil {
           log.Fatal(err)
       }

       fmt.Println("Waiting for messages. To exit, press Ctrl+C")
       for message := range messages {
           fmt.Printf("Received: %s\n", message.Body)
       }
   }

Remember to replace the connection details (localhost:5672) with the actual RabbitMQ server information. Also, ensure that RabbitMQ is running and accessible from your applications.

These examples illustrate a basic setup for a message broker using RabbitMQ. Depending on your use case, you may need to implement additional features such as error handling, message acknowledgment, and more advanced configurations.

Related Articles