Connecting to MQ Light from a web app via WebSockets

How to subscribe to MQ Light notifications from a web app, via a WebSockets bridge

I’ve been working on a microservices app hosted on Bluemix. It’s one logical app, but it’s implemented and deployed as a bunch of separate Bluemix applications, each with it’s own separate responsibility.

I’m using MQ Light as asynchronous messaging between the apps. Each Bluemix app publishes notifications about changes to resources, and the status of long-running tasks.

mqlight on Bluemix

I won’t labour why or how we do this here, as it’s well covered in many other posts on microservices. For example:

…publish everything, however boring and insignificant it may seem to the rest of the system. Publishing is very lightweight and the publisher does not need to know whether 0 or 1000 other services are interested in that particular event, just fire and forget. This is extremely powerful and is what enables microservices to be built and deployed extremely quickly…

This is working well, but I also want a web app to be able to get some of these notifications.

If the web app has a resource open for editing, I want it to get a push notification if there are any changes to the resource.

If the web app started a long-running task, I want it to get push notifications of status changes.

I’ve done this by writing a small proxy, allowing a web app to subscribe to MQ Light topics and get the message via WebSockets.

Essentially, it’s an mqlight-WebSockets bridge.

mqlight with WebSockets on Bluemix

It’s a simple bit of code, but I’ve not found any mentions of anyone else doing this with mqlight so I’m sharing it in case it can be helpful to someone.

I’ve put a simplified copy of the code on GitHub at
github.com/dalelane/mqlight-websockets-bridge.

The interesting stuff is all here. It’s hopefully obvious what it’s doing, but a couple of quick pointers…

  • I’m using Primus as a wrapper around the WebSocket API, so you can swap out the implementation for your own preferred flavour
  • I’ve got a stub function which checks the topic strings that web clients are asking to subscribe to, so you can reject clients that try and subscribe to messages on topics that you might not want to expose.
    Or, if you have different topics for different sets of data, you might want some clients to only be able to subscribe to notifications about their own resources. You can add that sort of logic to check the topic string and make your decision here.

Tags: , ,

Comments are closed.