Azure functions is the “serverless” offering on Azure. Serverless doesn’t mean there aren’t any servers, but it’s rather a platform service where you can run your own snippets of code. Each code can be triggered, where it then can have an in and/or output. In terms of billing, you pay for the amount of runtime you consume.
Imagine having a stateless web front end which publishes state onto a queue or storage account. Then Azure functions is being triggered and your business logic starts. Sounds familiar? Yes, because that’s a typical flow you normally do in your application stacks. Now you can segment that even more into services you do not need to manage.
Today I’m going to show you a very brief demo on using an Azure Event Hub as trigger/input for an Azure function. So what’s the flow we’ll be doing?
- A client will put a message on the event hub queue
- This will trigger an Azure function
- The function will save the contents of the message onto a storage account
Sound simple right? And it actually is that simple to do too!
We’ll start off with creating an out-of-the-box eventhub ;
Nothing fancy here!
Now let’s create a function.
We’re using “event hub” as a trigger, and then this will also act as an “input”. I’ll be using a storage account as an output, as I want to save the messages there. The connection towards the eventhub might have been the most “tricky” one, but that was far from complex… Just create a new connection and add the connection string ;
Now let’s take a look at the code of this function…
I added the second line of code, and that was it. We can easily say this isn’t exactly rocket science… For me, this flow was the first time I used nodejs, and I was able to get this working.
As a client I started from the following code ; https://github.com/ytechie/eventhubs-js/
Here I updated the /config/config.json file ;
And I tweaked the example file to send two messages to the event hub ; nodejs sendmsg.js
These messages get sent to the eventhub, as seen in the monitoring…
We can see the events being processed in the logs ;
And suddenly they are in the storage account under the path I configured ;
What did I learn by doing this experiment?
- Setting up functions is very easy
- When doing a load test, I posted about a million messages onto my queue. Then I saw that I was getting connection drops when trying to push towards the storage account. So do not forget error handling! Which I kinda did not foresee…
- The eventhub trigger is also an input. I didn’t grasp that at first…
Anyhow, I hope this was insightful. Have fun experimenting!