Sample Python script for publish/subscribe messages to IBM Message Hub on Bluemix

Sample Python script for publish/subscribe messages to IBM Message Hub on Bluemix @ www.Vasilev.link DevOps consultant
Nov 24, 2016

Hello,
In this post I will write for IBM Message Hub service.
It is fully managed, cloud-based messaging service provided by IBM® .

First we have to create an account in IBM Bluemix.
In the catalog, we should select Message Hub and create an instance.
After we create the instance, there are some details that we need in order to proceed. In my sample, I am using python script with MQLight client. To use mqlight, we should create one topic named "MQLight" with one partition.
After that we can proceed with the desired topics creation. Screen of the topics:


IBM Message Hub



In the original example of IBM, there is more info how to configure and connect with different types of clients - Using an MQ Light API client
I will make it simple.

In the "Service Credentials" section of IBM Message Hub, we can see a simular picture with all info about the connection parameters.



IBM Message Hub Service credentials


We need only three parameters in order to use MQ Light client with python: 

- mqlight_lookup_url
- user
- password


To use the script, we need to have the "amqp" protocol URL.
Just copy the link from "mqlight_lookup_url" and paste it in the browser. Now we see the whole link amqps://....
We will use this in the script together with credentials.


PUBLISH Python script:

import mqlight
timeservice = "service amqps URL"
mhuser = "username from Service Credentials"
mhpassword = "password from Service Credentials"
security_options = {
    'user': str(mhuser),
    'password': str(mhpassword)
}
def on_started(err):
  client.send('demotopic/test1/demo2', 'Hello World! Publisher test for IBM Message Hub')
    print "send complete"
    time.sleep(1)
    client.stop()
    client = mqlight.Client(service=service,security_options=security_options,on_started=on_started)


SUBSCRIBE Python script:

import mqlight,time

service = "service amqps URL"
mhuser = "username from Service Credentials"
mhpassword = "password from Service Credentials"

security_options = {
      'user': str(mhuser),
      'password': str(mhpassword)
}
def on_started(err):
  client.subscribe('demotopic/test1/demo2', on_message=on_message)
def on_message(message_type, data, delivery):
  print(data)

client = mqlight.Client(service=service,security_options=security_options,on_started=on_started)


After we publish some messages, we can see the activity in a graph thanks to the tool - Grafana:

IBM Message Hub Grafana



Additionally, we can connect and transfer messages to existing qmanager with Secure gateway and Message connect services from Bluemix.