Channel in Golang and use case – part IIII (pubsub pattern)

Tram Ho

Preamble

  • Continuing the series, today is my sharing on how to re-implement the pubsub pattern using golang channel. Let’s go, guys!

Pubsub

pub-sub-messaging.png

  • First we’ll get a full definition from the wiki :
    In software architecture, publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published messages into classes without knowledge of which subscribers, if any , there may be .
  • Pubsub is a message pattern in which the publisher just sends the message and doesn’t care if any subscribers receive it and the messages will be sorted and sent regardless of whether there are any subscribers or not. Publishers and subscribers do not know each other’s existence. In some pubsub systems, there will be an additional component called a broker, which will be responsible for sorting and sending messages.
  • Pubsub or message queue is generally used quite commonly in micro-service architectures. It provides a method for services to communicate with each other asynchronously. In addition, we will have some use cases for messaging queues in real-world scenarios such as: Sending emails, Data post-processing, Batch updates for databases…

Use case 3: Build pubsub service with buffered channel

  • Based on the feature that the channel is a queue, I will have a simple demo about pubsub as follows:

    messageQueue : contains a list of messages to be processed.

    MessageChannel : communication channel between publishers and subscribers. MessageChannel will now act as the heart of the system.

    mapTopicMessage : contains a map between the topic and the list of message channels. A topic will be subscribed by many subscribers, so we will have a 1:N relationship. It acts as the management of topics and message channels.

  • Principle operate:
    messageQueue when receiving a new message, the service will filter out the list of MessageChannel corresponding to the topic of that message and send the new message to. Each subscriber will communicate with the MessageChannel to get the message.
  • Publish message
  • Register Subscription

    when there is a “register subscription” request, the service will return a MessageChannel . Subscriber will communicate with that MessageChannel to receive the message.
  • Subscribe
  • Running and see what happen!
  • Add more subscriber

Build a complete pubsub

  • to be continued…

Ending

  • to be continued…
Share the news now

Source : Viblo