How to send data to queue in azure service bus

In this article, we are going to user powershell script to How can we send data to queue in azure service bus which is an excellent way if you want to process some large existing data and does not want to overload the application instantly. So this mechanism provides a controlled way to perform such task with help of azure service bus queue.

How to send data to queue in azure service bus

As the name suggests azure service bus queue is a queue. Our applications can send messages to this queue and also can listen from this queue one by one. Services provides a simple way to decouple components completely and efficiently. Service bus stores message durably

In Services bus context there are two users

  1. Producers
  2. Consumers

Producers push messages to queue without the expectation of any response.

Consumers read messages from queue and have no obligation for producers on how to process the message

Therefore producers and consumers does not have to send or receive messages from queue at the same time respectively and both can process message at their own pace

There are two ways consumers can receive messages from service bus,

  1. Receive and Delete
  2. Peak and Lock

Now let’s get started with powershell script to push messages to service bus queue.

	[Parameter (Mandatory = $false)]
	$ResourceGroupName = "",
	[Parameter (Mandatory = $false)]
	$NamespaceName = "",
	[Parameter(Mandatory = $false)]
	$PolicyName = 'RootManageSharedAccessKey',
	[Parameter(Mandatory = $true)]
	[Parameter(Mandatory = $true)]
	[Parameter(Mandatory = $true)]
	[Parameter(Mandatory = $true)]
	[Parameter(Mandatory = $false)]

function Send-AzServiceBusMessage
	$continuationToken = $null

	$module = Get-InstalledModule -Name Az.ServiceBus

	if($module -ne $null)
		write-host "module avaiable"
		write-host "Az.ServiceBus module not avaiable download in progress"
		Install-Module -Name Az.ServiceBus -AllowClobber -force

	$primaryKey = (Get-AzServiceBusKey -ResourceGroupName $ResourceGroupName -Namespace $namespacename -Name $PolicyName).Primarykey

	$message = [pscustomobject] @{ "Body" = "{`"userId`":`"$userId`",`"lat`":$lat, `"long`": $long}"; }
	write-host "josn data $message"

	$body = $message.Body

	#set up the url parameters for the Invoke-WebRequest
	$uri = "https://$"+$ServiceBusName+"/messages"

	$origin = [DateTime]"1/1/1970 00:00"
	$Expiry = (Get-Date).AddMinutes(1)

	#compute the token expiration time.
	$diff = New-TimeSpan -Start $origin -End $Expiry
	$tokenExpirationTime = [Convert]::ToInt32($diff.TotalSeconds)

	Add-Type -AssemblyName System.Web

	#create the string that will be hashed
	$stringToSign = [Web.HttpUtility]::UrlEncode($Namespace) + "`n" + $tokenExpirationTime

	#new-up the HMACSHA256 class
	$hmacsha = New-Object -TypeName System.Security.Cryptography.HMACSHA256
	$hmacsha.Key = [Text.Encoding]::UTF8.GetBytes($primaryKey)

	#hash is computed with the HMACSHA256 class instance. The hash is converted to a base 64 string
	$hash = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
	$signature = [Convert]::ToBase64String($hash)

	#creating token here
	$token = [string]::Format([Globalization.CultureInfo]::InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", [Web.HttpUtility]::UrlEncode($Namespace), [web.HttpUtility]::UrlEncode($signature),$tokenExpirationTime, $PolicyName)

	write-host "token : $token"

	$headers = @{"Authorization" = "$token"; "Content-Type" = "application/atom+xl;type=entry;charset-utf-g"}
	$headers.Add("BrokerProperties", $(ConvertTo-Json -InputObject $Message -Compress))

	#Invoke-WebRequest call.
	#This invokes the resurce api to push payload to service bus queue
	Invoke-WebRequest -Uri $uri -Headers $headers -Method Post -Body $body > $null


And using this we can push our messages to service bus queues. Cheers !

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights