我可以在使用以下命令创建的React应用程序中从浏览器(React JS)在Azure服务总线中发送/接收消息:npm create vite@latest my-app--template与react版本18.3.1反应。配置是在vite.config.js中添加nodePolyfills,安装process、util、stream-browserify、path buffer、os-browserify,并在config-corrides.jsx中配置这些包。使用此配置,我解决了 webpack 错误并成功将消息发送到主题/队列。我已经使用了这个版本的包“@azure/service-bus”:^7.9.5”。
现在我想在使用以下命令创建的 React 应用程序中使用 Azure 服务总线从浏览器发送/接收消息:npm create-react-app my-app(React 版本为 16.13.1)。我尝试将此“@azure/service-bus”包与此版本“^7.5.0”一起使用,因为在这里我不需要进行 webpack 配置,也没有收到任何类似“进程未定义”的错误,但是我无法向 Azure 服务总线发送消息。 所以我想知道我需要什么类型的配置来使用与浏览器兼容的 Node.js“@azure/service-bus”库,并向 Azure 服务总线发送/接收消息,就像我在 Vite + 中所做的那样反应应用程序。如果您能够分享一些代码片段以及使用 Azure 服务总线库(可与浏览器配合使用)完成的配置,那将会很有帮助,这样我就能抢占先机。
我尝试使用以下 ReactJS 和 Vite 项目在浏览器中向 Azure 服务总线队列和主题发送和接收消息。
这是完整的 GitHub 存储库。
AzureServiceBusComponent.jsx:
import React, { useState } from 'react';
import { ServiceBusClient } from '@azure/service-bus';
import { setLogLevel } from '@azure/logger';
setLogLevel('verbose');
const safeTrim = (value) => (value || '').trim();
const queueConnectionString = safeTrim(import.meta.env.VITE_QUEUE_CONNECTION_STRING);
const topicConnectionString = safeTrim(import.meta.env.VITE_TOPIC_CONNECTION_STRING);
const queueName = safeTrim(import.meta.env.VITE_QUEUE_NAME);
const topicName = safeTrim(import.meta.env.VITE_TOPIC_NAME);
const subscriptionName = safeTrim(import.meta.env.VITE_SUBSCRIPTION_NAME);
const timeOutInMs = Number(import.meta.env.VITE_TIMEOUT_IN_MS) || 60000;
function AzureServiceBusComponent() {
const [responseMessage, setResponseMessage] = useState('');
const [receivedQueueMessages, setReceivedQueueMessages] = useState([]);
const [receivedTopicMessages, setReceivedTopicMessages] = useState([]);
if (!queueConnectionString || !topicConnectionString) {
console.error("Azure Service Bus connection strings are not defined.");
return null;
}
const queueClient = new ServiceBusClient(queueConnectionString, {
retryOptions: {
timeoutInMs: timeOutInMs,
},
});
const topicClient = new ServiceBusClient(topicConnectionString, {
retryOptions: {
timeoutInMs: timeOutInMs,
},
});
const queueSender = queueClient.createSender(queueName);
const topicSender = topicClient.createSender(topicName);
const sendMessageToQueue = async () => {
try {
await queueSender.sendMessages({ body: 'Hello Kamali, sent to Queue!' });
setResponseMessage('Message sent to queue successfully!');
} catch (error) {
console.error('Error sending message to queue:', error);
}
};
const sendMessageToTopic = async () => {
try {
await topicSender.sendMessages({ body: 'Hello Kamali, sent to Topic!' });
setResponseMessage('Message sent to topic successfully!');
} catch (error) {
console.error('Error sending message to topic:', error);
}
};
const receiveMessagesFromQueue = async () => {
const receiver = queueClient.createReceiver(queueName, { receiveMode: 'receiveAndDelete' });
try {
const messages = await receiver.receiveMessages(5);
const newMessages = messages.map((msg) => msg.body);
setReceivedQueueMessages((prev) => [...prev, ...newMessages]);
} catch (error) {
console.error('Error receiving messages from queue:', error);
} finally {
await receiver.close();
}
};
const receiveMessagesFromTopic = async () => {
const receiver = topicClient.createReceiver(topicName, subscriptionName, { receiveMode: 'receiveAndDelete' });
try {
const messages = await receiver.receiveMessages(5);
const newMessages = messages.map((msg) => msg.body);
setReceivedTopicMessages((prev) => [...prev, ...newMessages]);
} catch (error) {
console.error('Error receiving messages from topic:', error);
} finally {
await receiver.close();
}
};
return (
<div>
<h2>Azure Service Bus</h2>
<button onClick={sendMessageToQueue}>Send Message to Queue</button>
<button onClick={sendMessageToTopic}>Send Message to Topic</button>
{responseMessage && <p>{responseMessage}</p>}
<div>
<h3>Received Queue Messages</h3>
<button onClick={receiveMessagesFromQueue}>Receive Messages from Queue</button>
<ul>
{receivedQueueMessages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
</div>
<div>
<h3>Received Topic Messages</h3>
<button onClick={receiveMessagesFromTopic}>Receive Messages from Topic</button>
<ul>
{receivedTopicMessages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
</div>
</div>
);
}
export default AzureServiceBusComponent;
.env:
VITE_QUEUE_CONNECTION_STRING=<queueconestring>
VITE_TOPIC_CONNECTION_STRING=<topicconnestring>
VITE_QUEUE_NAME=<queuename>
VITE_TOPIC_NAME=<topicname>
VITE_SUBSCRIPTION_NAME=<subname>
VITE_TIMEOUT_IN_MS=60000
输出:
我成功地向 Azure 服务总线队列发送和接收消息,如下所示。
发送时,我在 Azure 服务总线队列中收到以下消息。
我成功地向 Azure 服务总线主题发送和接收消息,如下所示。
发送时,我在 Azure 服务总线主题中收到以下消息。