釋出了新的觸發器 MNS 主題觸發器,這标志着函數計算的事件源新增加了一名成員 --
消息服務(簡稱 MNS))主題, 但是根據官方文檔
MNS主題觸發器描述,還存在以下幾個 region 的 MNS Topic 不能支援 MNS 主題觸發器:香港, 亞太東北 1(東京), 亞太東南 1(新加坡), 美國西部1(矽谷)。
問題
Q:這幾個 region 的 Topic 就不能利用函數計算的 serverless 能力了嗎?
A:老司機告訴你, 這個是可以的, 下面來看看怎麼在秋名山上玩漂移。

解決方案
1. 建立函數,設定 http trigger , 記得權限設定為匿名通路
2. 在 topic 上 訂閱的推送類型為 http
, 然後把函數設定http trigger 生成url 填入 接收端位址
http
接收端位址
注意:url 不要以 /
結尾,不然可能觸發不了函數,後面記得填充一個任意的 path 值.
- 函數設定 http trigger
不走尋常路--MNS主題觸發器的補充新玩法 - topic 增加 http 訂閱
不走尋常路--MNS主題觸發器的補充新玩法
發送消息到MNS主題實用代碼片段
函數計算 python/nodejs/php 執行環境都已經内置有mns的相關sdk,直接編寫相應的函數對MNS 進行操作即可,下面示例都是針對publish message 到 MNS 主題。
- python
# -*- coding: utf-8 -*- import logging from mns.account import Account from mns.topic import DirectMailInfo, DirectSMSInfo, TopicMessage access_key_id=<your ak id> access_key_secret=<your ak secret> endpoint = "http://<region>.mns.cn-qingdao.aliyuncs.com/" def handler(event, context): logger = logging.getLogger() logger.info(event) my_account = Account(endpoint, access_key_id, access_key_secret) topic_name = "test-topic" my_topic = my_account.get_topic(topic_name) #init TopicMessage msg_body = "I am test message." msg = TopicMessage(msg_body, "msg_tag") try: re_msg = my_topic.publish_message(msg) print "Publish Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id) except MNSExceptionBase,e: if e.type == "TopicNotExist": print "Topic not exist, please create it." sys.exit(1) print "Publish Message Fail. Exception:%s" % e return 'hello world'
- nodejs
var AliMNS = require("ali-mns"); var account = new AliMNS.Account("<your-account-id>", "<your-key-id>", "<your-key-secret>"); var topic = new AliMNS.Topic(<topicName>, account, 'qingdao'); module.exports.handler = function(event, context, callback) { console.log('hello world'); // send message topic.publishP("Hello MNS topic").done(function (data) { callback(null, data); }); };
- php
<?php use AliyunMNS\Client; use AliyunMNS\Requests\PublishMessageRequest; $accessId="<your-key-id>"; $accessKey="<your-key-secret>"; $endPoint = "http://<your-account-id>.mns.cn-qingdao.aliyuncs.com/"; $client = new Client($endPoint, $accessId, $accessKey); function handler($event, $context) { $topicName = "test-topic"; global $client; $topic = $client->getTopicRef($topicName);//擷取Topic位址 $messageBody = 'test message'; //消息内容 $messageTag = 'pay_success'; //消息标簽 $request = new PublishMessageRequest($messageBody,$messageTag); $res = $topic->publishMessage($request); $res->isSucceed(); return "OK"; }