Azure Service Bus kuyruklarında (JavaScript) ileti gönderme ve bu kuyruklardan ileti alma
Bu öğreticide, bir JavaScript programında paketi kullanarak bir uygulama kuyruğuna ileti göndermeyi ve bu kuyruktan @azure/service-bus ileti Service Bus öğrenirsiniz.
Not
Bu hızlı başlangıç, basit bir kuyruğa ileti gönderme ve bunları alma senaryosu için Service Bus adım yönergeler sağlar. Azure Service Bus için önceden yazılmış JavaScript ve TypeScript örneklerini GitHub.
Önkoşullar
- Azure aboneliği. Bu öğreticiyi tamamlamak için bir Azure hesabınızın olması gerekir. MSDN abone avantajlarınızı etkinleştirebilirsiniz veya ücretsiz bir hesaba kaydolabilirsiniz.
- Üzerinde çalışılacak bir kuyruğuz yoksa, kuyruk oluşturmak için Azure portal kuyruğu oluşturmak için Service Bus kullanma makalesinde yer alan adımları izleyin. Oluşturduğunuz kuyruğun adını ve Service Bus için bağlantı dizesini not edin.
Not
- Bu öğretici, Nodejs kullanarak kopyalayıp çalıştırarak örneklerle çalışır. Node.js uygulaması oluşturma yönergeleri için bkz. Node.jsuygulaması oluşturma ve azure web sitesine dağıtma veyaNode.js kullanarak bulut hizmetine Windows PowerShell.
Paketi yüklemek için Düğüm Paket Yöneticisi’ni (NPM) kullanma
Service Bus için npm paketini yüklemek için yolunda olan bir komut istemi açın, dizini, örneklerinizi almak istediğiniz klasörle değiştirin ve ardından npm bu komutu çalıştırın.
npm install @azure/service-bus
Kuyruğa ileti gönderme
Aşağıdaki örnek kod, kuyruğa nasıl ileti gönderebilirsiniz?
gibi sık kullanılan düzenleyiciniziVisual Studio Code.
adlı bir dosya
send.jsoluşturun ve aşağıdaki kodu dosyaya yapıştırın. Bu kod, bilim insanlarının adlarını kuyruğuna ileti olarak gönderir.const { ServiceBusClient } = require("@azure/service-bus"); // connection string to your Service Bus namespace const connectionString = "<CONNECTION STRING TO SERVICE BUS NAMESPACE>" // name of the queue const queueName = "<QUEUE NAME>" const messages = [ { body: "Albert Einstein" }, { body: "Werner Heisenberg" }, { body: "Marie Curie" }, { body: "Steven Hawking" }, { body: "Isaac Newton" }, { body: "Niels Bohr" }, { body: "Michael Faraday" }, { body: "Galileo Galilei" }, { body: "Johannes Kepler" }, { body: "Nikolaus Kopernikus" } ]; async function main() { // create a Service Bus client using the connection string to the Service Bus namespace const sbClient = new ServiceBusClient(connectionString); // createSender() can also be used to create a sender for a topic. const sender = sbClient.createSender(queueName); try { // Tries to send all messages in a single batch. // Will fail if the messages cannot fit in a batch. // await sender.sendMessages(messages); // create a batch object let batch = await sender.createMessageBatch(); for (let i = 0; i < messages.length; i++) { // for each message in the array // try to add the message to the batch if (!batch.tryAddMessage(messages[i])) { // if it fails to add the message to the current batch // send the current batch as it is full await sender.sendMessages(batch); // then, create a new batch batch = await sender.createMessageBatch(); // now, add the message failed to be added to the previous batch to this batch if (!batch.tryAddMessage(messages[i])) { // if it still can't be added to the batch, the message is probably too big to fit in a batch throw new Error("Message too big to fit in a batch"); } } } // Send the last created batch of messages to the queue await sender.sendMessages(batch); console.log(`Sent a batch of messages to the queue: ${queueName}`); // Close the sender await sender.close(); } finally { await sbClient.close(); } } // call the main function main().catch((err) => { console.log("Error occurred: ", err); process.exit(1); });yerine
<CONNECTION STRING TO SERVICE BUS NAMESPACE>ad alanınıza bağlantı dizesini Service Bus değiştirin.yerine
<QUEUE NAME>kuyruğun adını yazın.Ardından komut isteminde komutunu çalıştırarak bu dosyayı yürütün.
node send.jsAşağıdaki çıkışı görmelisiniz.
Sent a batch of messages to the queue: myqueue
Kuyruktan ileti alma
Sık kullanılan düzenleyicinizi açın, örneğin Visual Studio Code
adlı bir dosya
receive.jsoluşturun ve içine aşağıdaki kodu yapıştırın.const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus"); // connection string to your Service Bus namespace const connectionString = "<CONNECTION STRING TO SERVICE BUS NAMESPACE>" // name of the queue const queueName = "<QUEUE NAME>" async function main() { // create a Service Bus client using the connection string to the Service Bus namespace const sbClient = new ServiceBusClient(connectionString); // createReceiver() can also be used to create a receiver for a subscription. const receiver = sbClient.createReceiver(queueName); // function to handle messages const myMessageHandler = async (messageReceived) => { console.log(`Received message: ${messageReceived.body}`); }; // function to handle any errors const myErrorHandler = async (error) => { console.log(error); }; // subscribe and specify the message and error handlers receiver.subscribe({ processMessage: myMessageHandler, processError: myErrorHandler }); // Waiting long enough before closing the sender to send messages await delay(20000); await receiver.close(); await sbClient.close(); } // call the main function main().catch((err) => { console.log("Error occurred: ", err); process.exit(1); });yerine
<CONNECTION STRING TO SERVICE BUS NAMESPACE>ad alanınıza bağlantı dizesini Service Bus değiştirin.yerine
<QUEUE NAME>kuyruğun adını yazın.Ardından, bu dosyayı yürütmek için komut isteminde komutunu çalıştırın.
node receive.jsAşağıdaki çıkışı görmelisiniz.
Received message: Albert Einstein Received message: Werner Heisenberg Received message: Marie Curie Received message: Steven Hawking Received message: Isaac Newton Received message: Niels Bohr Received message: Michael Faraday Received message: Galileo Galilei Received message: Johannes Kepler Received message: Nikolaus Kopernikus
Service Bus ad Azure portal genel bakış sayfasında gelen ve giden ileti sayısını görebilirsiniz. En son değerleri görmek için bir dakika kadar beklemeniz ve sayfayı yenilemeniz gerekir.
Bu Genel Bakış sayfasında kuyruğu seçerek Kuyruk Service Bus gidin. Bu sayfada gelen ve giden ileti sayısını da görebilirsiniz. Ayrıca kuyruğun geçerli boyutu, maksimum boyut, etkin ileti sayısı gibi diğer bilgileri de görüyorsunuz.
Sonraki adımlar
Aşağıdaki belgelere ve örneklere bakın: