且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不走寻常路--MNS主题触发器的补充新玩法

更新时间:2022-06-25 06:57:43

函数计算发布了新的触发器 MNS 主题触发器,这标志着函数计算的事件源新增加了一名成员 -- 消息服务(简称 MNS))主题, 但是根据官方文档MNS主题触发器描述,还存在以下几个 region 的 MNS Topic 不能支持 MNS 主题触发器:***, 亚太东北 1(东京), 亚太东南 1(新加坡), 美国西部1(硅谷)。

问题

Q:这几个 region 的 Topic 就不能利用函数计算的 serverless 能力了吗?

A:老司机告诉你, 这个是可以的, 下面来看看怎么在秋名山上玩漂移。

不走寻常路--MNS主题触发器的补充新玩法

解决方案

不走寻常路--MNS主题触发器的补充新玩法

1. 创建函数,设置http trigger, 记得权限设置为匿名访问

2. 在 topic 上 订阅的推送类型为 http, 然后把函数设置http trigger 生成url 填入 接收端地址

注意: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";
    }