一直没有使用这个CSDN写文章,已经2年了,习惯于Github上写文章。抱歉没有维护。
Google CloudPlatform集成了许多的功能,包含数据存储,Compute Engine..等等。
要使用Google CloudPlatform首先得有帐号需要1美元购买体验
当你支付后就会变成这样
第一步创建项目
首先创建项目可以看谷歌官方文档
重要的部分
1.怎么样去创建Pub/Sub主题?
2.怎么去实现官方的代码?
3.怎么去合理使用 function方法?
首先下载官方的demo
demo 包含有 node.js版本和python版本
为了快速开发推荐使用node.js版本
https://github.com/GoogleCloudPlatform/nodejs-docs-samples
//官方 python-docs-samples
https://github.com/GoogleCloudPlatform/python-docs-samples
下载之后先看一下不着急进行
下面我们要了解 firebase functions 因为我们需要把代码运行到firebase functions中去
https://github.com/firebase/functions-samples
这一段代码是正儿八经的mqtt pub/sub的关键 没有这一段代码这个项目无法做
通过这代码中的这一段代码
创建PUB/SUB
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// [START import]
const functions = require('firebase-functions');
// [END import]
// [START helloWorld]
/**
* Cloud Function to be triggered by Pub/Sub that logs a message using the data published to the
* topic.
*/
// [START trigger]
exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish((message) => {
// [END trigger]
// [START readBase64]
// Decode the PubSub Message body.
const messageBody = message.data ? Buffer.from(message.data, 'base64').toString() : null;
// [END readBase64]
// Print the message in the logs.
console.log(`Hello ${messageBody || 'World'}!`);
return null;
});
// [END helloWorld]
/**
* Cloud Function to be triggered by Pub/Sub that logs a message using the data published to the
* topic as JSON.
*/
exports.helloPubSubJson = functions.pubsub.topic('another-topic-name').onPublish((message) => {
// [START readJson]
// Get the `name` attribute of the PubSub message JSON body.
let name = null;
try {
name = message.json.name;
} catch (e) {
console.error('PubSub message was not JSON', e);
}
// [END readJson]
// Print the message in the logs.
console.log(`Hello ${name || 'World'}!`);
return null;
});
/**
* Cloud Function to be triggered by Pub/Sub that logs a message using the data attributes
* published to the topic.
*/
exports.helloPubSubAttributes = functions.pubsub.topic('yet-another-topic-name').onPublish((message) => {
// [START readAttributes]
// Get the `name` attribute of the message.
const name = message.attributes.name;
// [END readAttributes]
// Print the message in the logs.
console.log(`Hello ${name || 'World'}!`);
return null;
});
所有的数据发送都是通过这段函数
现在更换了github 发表文章