Bir Azure Service Bus konu başlığına ileti gönderme ve aboneliklerden konuya ileti alma (JavaScript)
Bu öğreticide, paketi bir JavaScript programında kullanarak bir Service Bus konu başlığına ileti göndermeyi ve bu konuya Service Bus @azure/service-bus ileti göndermeyi öğrenirsiniz.
Not
Bu hızlı başlangıç, bir konu başlığına toplu ileti gönderme ve bu iletileri konu aboneliğinden Service Bus basit bir senaryo için adım 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 hesap için kaydolabilirsiniz.
- Hızlı Başlangıç: Konusuyla ilgili Azure portal ve abonelikler Service Bus için hızlı başlangıç adımlarını izleyin. Bağlantı dizesini, konu adını ve abonelik adını not edin. Bu hızlı başlangıç için yalnızca bir abonelik kullanasınız.
Not
- Bu öğretici, Nodejs kullanarak kopyalayıp çalıştırarak örneklerle çalışır. Node.js uygulaması oluşturma yönergeleri için bkz. Node.js uygulaması oluşturma ve azure websitesine dağıtma veya Windows PowerShell kullanarakNode.js Cloud Service.
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
Konu başlığına ileti gönderme
Aşağıdaki örnek kod, bir konu başlığına toplu ileti Service Bus gösterir. Ayrıntılar için kod açıklamalarını görme.
Sık kullanılan düzenleyicinizi açın, örneğin Visual Studio Code
adlı bir dosya
sendtotopic.jsoluşturun ve aşağıdaki kodu dosyaya yapıştırın. Bu kod, konu başlığınıza bir ileti gönderir.const { ServiceBusClient } = require("@azure/service-bus"); const connectionString = "<SERVICE BUS NAMESPACE CONNECTION STRING>" const topicName = "<TOPIC 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 queue. const sender = sbClient.createSender(topicName); 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 arry // 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 topic await sender.sendMessages(batch); console.log(`Sent a batch of messages to the topic: ${topicName}`); // 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
<SERVICE BUS NAMESPACE CONNECTION STRING>ad alanınıza bağlantı dizesini Service Bus değiştirin.yerine
<TOPIC NAME>konunun adını yazın.Ardından komut isteminde komutunu çalıştırarak bu dosyayı yürütün.
node sendtotopic.jsAşağıdaki çıkışı görmelisiniz.
Sent a batch of messages to the topic: mytopic
Abonelikten ileti alma
Sık kullanılan düzenleyicinizi açın, örneğin Visual Studio Code
receivefromsubscription.js adlı bir dosya oluşturun ve içine aşağıdaki kodu yapıştırın. Ayrıntılar için kod açıklamalarını görme.
const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus"); const connectionString = "<SERVICE BUS NAMESPACE CONNECTION STRING>" const topicName = "<TOPIC NAME>"; const subscriptionName = "<SUBSCRIPTION 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 queue. const receiver = sbClient.createReceiver(topicName, subscriptionName); // 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(5000); await receiver.close(); await sbClient.close(); } // call the main function main().catch((err) => { console.log("Error occurred: ", err); process.exit(1); });yerine
<SERVICE BUS NAMESPACE CONNECTION STRING>ad alanının bağlantı dizesini ekleyin.yerine
<TOPIC NAME>konunun adını yazın.yerine
<SUBSCRIPTION NAME>konu aboneliğinin adını yazın.Ardından komut isteminde komutunu çalıştırarak bu dosyayı yürütün.
node receivefromsubscription.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
Aşağıdaki Azure portal, Service Bus ad alanınıza gidin ve alt bölmede konuyu seçerek konu başlığınıza Service Bus konu başlığı sayfasını görüntüleyin. Bu sayfada İletiler grafiğinde üç gelen ve üç giden ileti görüyorsanız.
Bir sonraki sefer yalnızca gönderme uygulamasını çalıştırıyorsanız, Service Bus Konu Başlığı sayfasında altı gelen ileti (3 yeni) ama üç giden ileti görebilirsiniz.
Bu sayfada, bir abonelik seçersiniz, Abonelik sayfasında Service Bus edinebilirsiniz. Bu sayfada etkin ileti sayısını, ileti sayısını ve daha fazlasını görebilirsiniz. Bu örnekte, henüz bir alıcı tarafından alınmış üç etkin ileti vardır.
Sonraki adımlar
Aşağıdaki belgelere ve örneklere bakın: