Freigeben über


Node.js in Azure Web Sites and Service Bus - Installing tools and Reading Messages from Cloud-hosted Queues

This post is about reading Service Bus Queues messages from Node.js.

  1. Creating the queues

  2. Populating the queues

  3. Downloading Web Matrix

  4. Setting up node

  5. Configuring Azure

  6. Writing Code

  7. Reading Service Bus Queues

  8. Testing it locally

The last blog post

  1. https://blogs.msdn.com/b/brunoterkaly/archive/2014/08/07/learn-how-to-create-a-queue-place-and-read-a-message-using-azure-service-bus-queues-in-5-minutes.aspx

Code to create and populate queue

Populate SB Queue
1 2 3 4 5 6 7 8         NamespaceManager namespaceManager = NamespaceManager.Create();         Console.WriteLine("\nCreating Queue '{0}'...", QueueName);         // Delete if exists         if (namespaceManager.QueueExists(QueueName))         {             namespaceManager.DeleteQueue(QueueName);         }         namespaceManager.CreateQueue(QueueName);

Code to Define message type

Define Msg Type
1 2 3 4 5 6   private static BrokeredMessage CreateSampleMessage(string messageId, string messageBody)     {         BrokeredMessage message = new BrokeredMessage(messageBody);         message.MessageId = messageId;         return message;     }

Code to Write to queue

Write to Queue
1 queueClient.Send(message);

Error recovery

Error Recovery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 catch (MessagingException e)     {     if (!e.IsTransient)     {         Console.WriteLine(e.Message);         throw;     }     ....                    // If we hit error, wait a couple of seconds and loop again private static void HandleTransientErrors(MessagingException e)     {         //If transient error/exception, let's back-off for 2 seconds and retry         Console.WriteLine(e.Message);         Console.WriteLine("Will retry sending the message in 2 seconds");         Thread.Sleep(2000);     }

This post is about getting node to read service bus queue messages

The primary goal here is get node up and running and have a reasonable IDE to work with. Web Matrix is a great tool

Install Web Matrix

image001

Figure 1: Installing Web Matrix

Installing Node

Let's get Node installed at the point. The download link for node is https://nodejs.org/

image002

Figure 2: Installing Node.js on Windows

After installation

All the node files you will need are now find here c:\program files\nodejs

Starting web matrix and starting new project

We have already installed Web Matrix. It is time to start writing hello world. Select from the template gallery.

From the File menu, choose Site from Template Gallery

image003

Figure 3: Web Matrix Template Gallery

Viewing the default project

You will need to provide a site name. An Azure Web Site will be provisioned for you. This will be where we deploy to once we are ready.

image004

Figure 4: Defining An Azure Web Site

Getting your project's folder

If you right mouse click in the solution you can choose ?Show file in Explorer.? This allows you to easily navigate to the folder if you copy the path to your clipboard. We will navigate to our project folder so we can install the azure node packages. We will run the utility ?npm? which allows you to install new packages from the npm website directly into our node project from Web Matrix.

image005

Figure 5: Getting to the project folder

The command line

The command line is where you will actually add the needed node packages.

image006

Figure 6: The command line

Adjusting the path

You will need to fix your path to make sure the node executables are available.

image007

Figure 7: Setting the Path

A simple NPM command

Note that we have some parameters available through NPM.

image008

Figure 8: Using NPM

Install the Azure Package

Simply type in npm install azure

image009

Figure 9: Installing the Azure Package

Verifying the package(s)

You can see below we have a number of modules installed. You can expand the node_modules folder to see what is installed.

image010

Figure 10: Viewing the Package

Writing some node.js code

Now we can start writing the code for node.js.

One of the first things you will need is the connection string for your Service Bus connection. You can get this at the portal.

You can also get it from the portal as seen below.

image011

Figure 11: Getting the Service Bus Connection String

Some Node.js code (server.js)

Here is some code to read messages from the Azure Service Bus Queue.

Main Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 var azure = require('azure'); var http = require('http'); var queue = 'samplequeue';   var error;     http.createServer(function (req, res) {       var connString1 = 'Endpoint=sb://smartdoorqueue-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[get this from the portal]';       console.log('createServiceBusService2()');       // Crucial function call to get connected. Make sure you have the proper     // configuration with auzre to run     serviceBusServiceClient = azure.createServiceBusService(connString1);     console.log('create topic()');     serviceBusServiceClient.createTopicIfNotExists('MyTopic3', function (error) {         if (!error) {             // Topic was created or exists             console.log('topic created or exists.');         }         else {             console.log(error);         }     });       // Helps with error tracking     console.log('call receiveMessage()');           receiveMessages();       // Get rid of output to browser for now     //res.writeHead(200, { 'Content-Type': 'text/html' });     //res.end('Hello, world 6!');   }).listen(process.env.PORT || 8081);     // Here is the code that will receive the first 2 messages in the queue.   function receiveMessages() {   // Step 2: Receive the messages.   serviceBusServiceClient.receiveQueueMessage(queue, true, function (error1, message1) {     if (error1) {       console.log(error1);     } else {       console.log(message1.body);       serviceBusServiceClient.receiveQueueMessage(queue, true, function (error2, message2) {         if (error2) {           console.log(error2);         } else {           console.log(message2.body);         }       });     }   }); }           /* OLD HELLO WORLD CODE var http = require('http');   http.createServer(function (req, res) {         res.writeHead(200, { 'Content-Type': 'text/html' });     res.end('Hello, world!');     }).listen(process.env.PORT || 8080);     */

Viewing the output from the messages in the queue

Now it is a simple case of running the code by hitting Run from the WebMatrix Toolbar. Here is what the output looks like:

image013

Figure 13: Viewing Message from the Service Bus Queue

Conclusion

This is a simple post that illustrates how you can use Node.js to read messages from the Azure Service Bus.