All Products
Search
Document Center

MNS topic trigger

Last Updated: Apr 03, 2019

Alibaba Cloud Message Service (MNS) is an efficient, reliable, secure, convenient, and scalable distributed message service. MNS enables application developers to easily transfer data and notification messages between distributed components, and build loosely coupled systems. In Message Service, publishers can use the PublishMessage API to publish messages to topics. Topic subscribers can then receive these messages. MNS and Function Compute (FC) have now been integrated to provide MNS topics as event sources, which allow you to use functions as topic subscribers. This enables you to process messages that are published to topics using custom functions in a timely manner.

mns-fc

As shown in the above figure, MNS topics support certain types of subscribers. However, the service does not provide the following advanced features:

  • The service does not support advanced processing before sending messages to email or SMS services.
  • You need backend services in order to use HTTP endpoints.
  • Custom processing options are limited. For example, you cannot directly send messages to slack or persistently store specific types of messages.

MNS topic triggers are introduced to solve above issues. Note the following restrictions if you are using MNS topic triggers for the first time.

Region restrictions

The following restrictions apply to the use of MNS topics only.

Regions that fully support MNS topic triggers

Australia (Sydney), India (Mumbai), China (Zhangjiakou), US (Virginia), and Indonesia (Djakarta), China (Huhehaote).

Notes on Chinese regions:

China (Qingdao), China (Beijing), China (Hangzhou), China (Shanghai), and China (Shenzhen)

Currently, MNS topic triggers are in beta testing. To use the service, you need to submit an application.

In the Function Compute console, you can select regions on the MNS topic trigger page. If the selected region does not support MNS topic triggers, you can click Sign up MNS Trigger Beta to apply for.

Currently, the following regions do not support MNS topic triggers: Hong Kong, Japan (Tokyo), Singapore, Germany (Frankfurt), and US (Silicon Valley).

Limits

  • We recommend that you select the same region for the MNS topic and function.

    MNS topic triggers support topics and functions in different regions. However, the network latency will increase due to the difference in region, especially when one of the region is in Mainland China and the other is not.

  • We recommend that you avoid recursive calls.

    Note that you must avoid recursive calls in your code. For example, if topic A triggers function B, do not use function B to publish new messages to topic A.

Event definition

The message published to an MNS topic is passed to the handler of the function as the event parameter.

Configure an MNS topic trigger

Trigger example: mns_topic_trigger.yml

  1. triggerConfig:
  2. notifyContentFormat: STREAM
  3. notifyStrategy: BACKOFF_RETRY
  4. filterTag: testTag

Trigger parameter description:

Name Constraint Default Type Desc
notifyContentFormat STREAM, JSON STREAM string notification event format
notifyStrategy BACKOFF_RETRY, EXPONENTIAL_DECAY_RETRY BACKOFF_RETRY string Optional, details refer to NotifyStrategy
filterTag The value is a string of no more than 16 characters. The default value is no message filter. string Optional, Message filter tag in the created subscription (Only messages with consistent tags are pushed.)

The event parameters sample

  • NotifyContentFormat is STREAM, sample event about message have attr and no attr

    1. 'hello topic'
    1. {
    2. "body": "hello topic",
    3. "attrs": {
    4. "Extend": "{\\"Context\\":\\"user custom info\\"}"
    5. }
    6. }
  • NotifyContentFormat is JSON, sample event about message have attr and no attr

    1. {
    2. "Context": "user custom info",
    3. "TopicOwner": "1186202104331798",
    4. "Message": "hello topic",
    5. "Subscriber": "1186202104331798",
    6. "PublishTime": 1550216302888,
    7. "SubscriptionName": "test-fc-subscibe",
    8. "MessageMD5": "BA4BA9B48AC81F0F9C66F6C909C39DBB",
    9. "TopicName": "test-topic",
    10. "MessageId": "2F5B3C281B283D4EAC694B7425288675"
    11. }
    1. ```json
    2. {
    3. "TopicOwner": "1186202104331798",
    4. "Message": "hello topic",
    5. "Subscriber": "1186202104331798",
    6. "PublishTime": 1550216480040,
    7. "SubscriptionName": "test-fc-subscibe",
    8. "MessageMD5": "BA4BA9B48AC81F0F9C66F6C909C39DBB",
    9. "TopicName": "test-topic",
    10. "MessageId": "2F5B3C082B923D4EAC694B76D928B5B8"
    11. }
    12. ```
  • sample code for topic to publish messages

    1. // Code examples written in the go language
    2. ...
    3. client := ali_mns.NewAliMNSClient(conf.Url,conf.AccessKeyId,conf.AccessKeySecret)
    4. topic := ali_mns.NewMNSTopic("test-topic", client)
    5. msg := ali_mns.MessagePublishRequest{
    6. MessageBody: "hello topic",
    7. //MessageTag: "testTag",
    8. MessageAttributes: &ali_mns.MessageAttributes{
    9. ExtendAttributes: &ali_mns.ExtendAttributes{
    10. Context: "user custom info",
    11. },
    12. },
    13. }
    14. _, err := topic.PublishMessage(msg)
    15. if err != nil {
    16. fmt.Println(err)
    17. return
    18. }

Example overview

You can set up an MNS topic trigger in the Function Compute console, using the fcli, or through SDKs. The following section gives an example for each method.

Example one: Create an MNS topic trigger in the console

This example demonstrates how to set up an MNS topic trigger in the console. You can set up a trigger when you are creating a function or after you have created the function. For more information about creating triggers, see Create a trigger and Configure triggers and events.

Log on to the Function Compute console, and select the region and service. If you have not created a service, see Create a service.

Set up a trigger when creating a function

  1. Click Create Function, select Empty Function, and click Next.

  2. Select MNS Topic Trigger.

  3. Create the function, specify the parameters, select In-line Edit, paste the following Python example code, and click Next.

  1. import logging
  2. def handler(event, context):
  3. # event is messages that posted on a topic
  4. logger = logging.getLogger()
  5. logger.info("mns topic trigger event = {}".format(event))
  6. return "OK"
  1. Configure permissions based on your needs and click Next. After you have confirmed the settings, click Create.

Set up a trigger after you have created the function

  1. Select the function you have created, click Triggers > Create Trigger.

  2. Configure the MNS topic trigger and click OK.

    Note: You may use Quick Authorize to speed up the authorization process.

Example two: Create an MNS topic trigger using the fcli

First, create a yaml file that contains Trigger Config. The yaml file is as follows:

  1. triggerConfig:

Create the trigger under the directory of the corresponding function.

  1. mkt triggerName serviceName/functionName -t mns_topic -c TriggerConfig.yaml -r acs:ram::$accountId:role/aliyunmnsnotificationrole -s acs:mns:cn-hangzhou:$accountId:/topics/$topicName
  • -r —invocation-role string Specify the trigger role.
  • -s —source-arn string Specify the ARN of the event source, for example, acs:mns:cn-hangzhou:123456:/topics/test-topic.
  • -c —trigger-config string Specify the trigger configuration file.
  • -t —type string Specify the type of the trigger.

For more information about fcli, see Tools - fcli.

Example three: Create an MNS topic trigger using SDKs

The following example uses the FC Python SDK to create an MNS topic trigger. Function Compute also provides the Node.js SDK and Java SDK.

Create the trigger

  1. client = fc2.Client(
  2. endpoint='<Your Endpoint>',
  3. accessKeyID='<Your AccessKeyID>',
  4. accessKeySecret='<Your AccessKeySecret>')
  5. service_name = 'serviceName'
  6. function_name = 'functionName'
  7. trigger_name = 'triggerName'
  8. trigger_type = 'mns_topic'
  9. source_arn = 'acs:mns:cn-hangzhou:<Your Account ID>:/topics/<Your topicName>'
  10. invocation_role = 'acs:ram::<Your Account ID>:role/<Your Invocation Role>'
  11. trigger_config = {}
  12. client.create_trigger(service_name, function_name, trigger_name, trigger_type, trigger_config, source_arn, invocation_role)

Create the function

  1. import logging
  2. def handler(event, context):
  3. # event is messages that posted on a topic
  4. logger = logging.getLogger()
  5. logger.info("mns topic trigger event = {}".format(event))
  6. # to do anything, for example, record event to tablestore
  7. return "OK"

If you have any problems, leave a comment or join the Function Compute customer support group (DingTalk group number: 11721331).