Google Cloud Pub/Sub: Node.js Client

Google Cloud Pub/Sub: Node.js Client

1. 啟用 API 服務

API 服務

2. 建立服務帳戶金鑰

建立服務帳戶金鑰

建立服務帳戶金鑰

3. 啟用驗證

將下載的檔案放到專案中並指定路徑

1
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

4. install Package

1
npm install @google-cloud/pubsub

5. Create Topic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Imports the Google Cloud client library
const { PubSub } = require('@google-cloud/pubsub');

async function quickstart(
projectId = 'your-project-id', // Your Google Cloud Platform project ID
topicName = 'my-topic' // Name for the new topic to create
) {
// Instantiates a client
const pubsub = new PubSub({ projectId });

// Creates the new topic
const [topic] = await pubsub.createTopic(topicName);
console.log(`Topic ${topic.name} created.`);
}
quickstart();

6. Create Subscription

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
async function createSubscription(topicName, subscriptionName) {
// [START pubsub_create_pull_subscription]
// Imports the Google Cloud client library
const { PubSub } = require('@google-cloud/pubsub');

// Creates a client
const pubsub = new PubSub();

/**
* TODO(developer): Uncomment the following lines to run the sample.
*/
// const topicName = 'my-topic';
// const subscriptionName = 'my-sub';

// Creates a new subscription
await pubsub.topic(topicName).createSubscription(subscriptionName);
console.log(`Subscription ${subscriptionName} created.`);

// [END pubsub_create_pull_subscription]
}
createSubscription('my-topic', 'my-topic-Subscription');

7. Push Message

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
async function publishMessage(topicName, data) {
// [START pubsub_publish]
// [START pubsub_quickstart_publisher]
// Imports the Google Cloud client library
const { PubSub } = require('@google-cloud/pubsub');

// Creates a client
const pubsub = new PubSub();

/**
* TODO(developer): Uncomment the following lines to run the sample.
*/
// const topicName = 'my-topic';
// const data = JSON.stringify({ foo: 'bar' });

// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);

const messageId = await pubsub.topic(topicName).publish(dataBuffer);
console.log(`Message ${messageId} published.`);

// [END pubsub_publish]
// [END pubsub_quickstart_publisher]
}
publishMessage('my-topic', 'TestData');

8. Pull Message

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function listenForMessages(subscriptionName, timeout) {
// [START pubsub_subscriber_async_pull]
// [START pubsub_quickstart_subscriber]
// Imports the Google Cloud client library
const { PubSub } = require('@google-cloud/pubsub');

// Creates a client
const pubsub = new PubSub();

/**
* TODO(developer): Uncomment the following lines to run the sample.
*/
// const subscriptionName = 'my-sub';
// const timeout = 60;

// References an existing subscription
const subscription = pubsub.subscription(subscriptionName);

// Create an event handler to handle messages
let messageCount = 0;
const messageHandler = message => {
console.log(`Received message ${message.id}:`);
console.log(`\tData: ${message.data}`);
console.log(`\tAttributes: ${message.attributes}`);
messageCount += 1;

// "Ack" (acknowledge receipt of) the message
message.ack();
};

// Listen for new messages until timeout is hit
subscription.on(`message`, messageHandler);

setTimeout(() => {
subscription.removeListener('message', messageHandler);
console.log(`${messageCount} message(s) received.`);
}, timeout * 1000);
// [END pubsub_subscriber_async_pull]
// [END pubsub_quickstart_subscriber]
}
listenForMessages('my-topic-Subscription', 3);

範例

Reference