Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Real-Time Broadcast Messaging with RabbitMQ for Frontend Applications

Tech 3

Core Concepts:

Exchange: A message router that defines routing rules. Queue: A buffer that holds messages. Channel: A connection for reading and writing messages. Binding: A link between a Queue and an Exchange, spceifying which messages (based on routing rules) go to which queue.

Select the appropriate subscription method based on business logic. Exchanges determine routing strategies and are categorized as follows:

  1. Direct Exchange: Routes messages based on an exact matching key.
  2. Topic Exchange: Routes messages using pattern matching on the key.
  3. Fanout Exchenge: Broadcasts messages to all bound queues, ignoring the routing key.

Back end: Publishing Messages

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.BindingBuilder;
import com.alibaba.fastjson.JSONObject;

@RestController
public class MessageBroadcastController {
    @Autowired
    private RabbitTemplate messagingTemplate;

    @GetMapping("/broadcast/price")
    public void broadcastPriceUpdate() {
        JSONObject messagePayload = new JSONObject();
        messagePayload.put("currentPrice", "987.65");
        
        // Define a queue (often done via configuration)
        Queue targetQueue = new Queue("PriceUpdatesQueue");
        // Declare a fanout exchange
        FanoutExchange broadcastExchange = new FanoutExchange("app.broadcast.exchange");
        // Bind the queue to the exchange
        BindingBuilder.bind(targetQueue).to(broadcastExchange);
        
        // Broadcast the message. The empty string is the routing key (ignored by Fanout).
        messagingTemplate.convertAndSend("app.broadcast.exchange", "", 
                                         messagePayload.toJSONString());
    }
}

Frontend: Subscribing to Messages

Ensure the correct destination path is used for subscription. The path can often be found in the browser's developer console network tab when the connection is established.

import Stomp from 'stompjs';

export default {
  data() {
    return {
      stompClient: null,
      brokerURL: 'ws://your-server:port/ws-endpoint',
      mqUser: 'guest',
      mqPass: 'guest',
      virtualHost: '/' // Optional, defaults to '/'
    }
  },
  methods: {
    connectToMessageBroker() {
      this.stompClient = Stomp.client(this.brokerURL);
      const connectHeaders = {
        login: this.mqUser,
        passcode: this.mqPass,
      };
      // Establish connection
      this.stompClient.connect(connectHeaders.login, connectHeaders.passcode, 
                               this.onConnectionSuccess, 
                               this.onConnectionError, 
                               this.virtualHost);
    },
    onConnectionSuccess: function() {
      // Subscribe to the specific exchange/queue binding.
      // Format: '/exchange/{exchangeName}/{queueName}'
      this.stompClient.subscribe('/exchange/app.broadcast.exchange/PriceUpdatesQueue', 
                                 this.handleIncomingMessage, 
                                 this.onSubscriptionError);
    },
    onConnectionError: function(errorFrame) {
      console.error('Connection failed:', errorFrame);
      // Implement user notification logic here
    },
    onSubscriptionError: function(errorFrame) {
      console.error('Subscription failed:', errorFrame);
    },
    handleIncomingMessage: function(messageFrame) {
      // Process the received message
      const messageBody = JSON.parse(messageFrame.body);
      const updatedPrice = messageBody.currentPrice;
      // Execute application-specific logic with the new data
      console.log('Price update received:', updatedPrice);
      // e.g., Update Vue component data or trigger a method
      this.$emit('price-updated', updatedPrice);
    },
    disconnectFromBroker() {
      if (this.stompClient) {
        this.stompClient.disconnect(() => {
          console.log('Disconnected from message broker.');
        });
      }
    }
  },
  beforeDestroy() {
    this.disconnectFromBroker();
  }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.