// 引入Google Cloud Pub/Sub Node.js客户端库
const {PubSub} = require('@google-cloud/pubsub');
// 创建一个PubSub客户端实例
const pubSubClient = new PubSub();
// 异步函数,用于创建一个新的主题
async function createTopic(topicName) {
// 尝试创建主题
try {
const [topic] = await pubSubClient.createTopic(topicName);
console.log(`主题 ${topicName} 创建成功.`);
return topic;
} catch (error) {
// 如果主题已存在,则会抛出错误,可以根据需要处理错误
if (error.code === 6) {
console.log(`主题 ${topicName} 已存在。`);
return pubSubClient.topic(topicName);
}
// 如果是其它错误,则重新抛出
throw error;
}
}
// 异步函数,用于向主题发送消息
async function publishMessage(topic, message) {
// 创建一个消息
const data = Buffer.from(message);
const messageId = await topic.publish(data);
console.log(`消息 ${message} 已发送,ID: ${messageId}`);
}
// 使用示例
const topicName = 'my-topic'; // 替换为你的主题名称
const message = 'Hello, Pub/Sub!'; // 替换为你想发送的消息
// 创建主题
createTopic(topicName)
.then(topic => {
// 发布消息
publishMessage(topic, message);
})
.catch(error => {
console.error('发生错误:', error);
});
这段代码展示了如何使用Google Cloud Pub/Sub Node.js客户端库创建一个主题,并向该主题发送一条消息。如果主题已存在,它会被客户端库识别并重用,而不会抛出错误。发送消息时,它会使用Buffer对象来保证消息内容的传输。