Last active
April 5, 2019 03:18
-
-
Save amtux/ffad7c00a56b919ce8c1b7f231b4949a to your computer and use it in GitHub Desktop.
Google Cloud Pubsub example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {PubSub} = require('@google-cloud/pubsub'); | |
const pubsub = new PubSub({ | |
projectId: 'some-project', | |
//apiEndpoint: 'localhost:8085' // for local emulator | |
}); | |
const topicName = 'sometopic'; | |
const subscriptionName = 'somesub'; | |
pubsub.topic(topicName).createSubscription(subscriptionName); | |
pubsub.createTopic(topicName) | |
.then(() => { | |
console.log(`Subscription ${subscriptionName} created.`); | |
}) | |
.then(() => { | |
pubsub.topic(topicName).createSubscription(subscriptionName); | |
}) | |
.catch((err) => { | |
console.log(`Failed to create subscription: ${subscriptionName}. err: ${err}`); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {PubSub} = require('@google-cloud/pubsub'); | |
const pubsub = new PubSub({ | |
projectId: 'some-project', | |
//apiEndpoint: 'localhost:8085' // for local emulator | |
}); | |
const timeout = 600; | |
const subscriptionName = 'somesub'; | |
const subscription = pubsub.subscription(subscriptionName); | |
let messageCount = 0; | |
const messageHandler = message => { | |
console.log('Received message', message.id); | |
console.log('\tData:',message.data); | |
console.log('\tData string:', message.data.toString()); | |
console.log('\tAttributes:', message.attributes); | |
messageCount += 1; | |
message.ack(); | |
}; | |
subscription.on(`message`, messageHandler); | |
setTimeout(() => { | |
subscription.removeListener('message', messageHandler); | |
console.log(`${messageCount} message(s) received.`); | |
}, timeout * 1000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {PubSub} = require('@google-cloud/pubsub'); | |
const pubsub = new PubSub({ | |
projectId: 'some-project', | |
//apiEndpoint: 'localhost:8085' // for local emulator | |
}); | |
const topicName = 'sometopic'; | |
const data = JSON.stringify({ foo: 'bar' }); | |
const dataBuffer = Buffer.from(data); | |
pubsub.topic(topicName).publish(dataBuffer). | |
then((messageId) => { | |
console.log(`Message ${messageId} published.`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment