文档

快速开始

更新时间:

本文以一个HelloWorld Serverless应用为例,介绍使用Fun工具构建应用的步骤。本示例包含创建一个HelloWorld应用,在本地类Link IoT Edge环境中测试应用,最后将应用部署到阿里云函数计算服务(云端)。

概述

使用Fun工具构建一个Serverless应用主要包含如下步骤:

  1. 初始化项目。使用fun init基于模板初始化应用项目。
  2. 本地测试。使用fun edge invoke等命令测试和调试您的应用。
  3. 发布(部署)。使用fun deploy将应用发布到云端后,您可以像使用其他函数一样,在Link IoT Edge中使用新开发的Serverless应用。

前提条件

在开始之前,请确保Fun已经正确安装和配置

操作步骤

  1. 初始化应用。
    Fun提供了非常便捷的方式来帮助您创建新项目,您可以在安装Fun的机器中任意位置创建项目目录,并在目录中执行fun init命令即可创建一个新的Serverless应用。
    重要 Link IoT Edge目前仅支持在Nodejs8和Python3中运行Serverless应用。
    $ mkdir helloworld
    $ cd helloworld/
    $ fun init
    ? Select a tempalte to init helloworld-nodejs8
    Start rendering template...
    + /private/tmp/helloworld
    + /private/tmp/helloworld/index.js
    + /private/tmp/helloworld/template.yml
    finish rendering template.

    其中template.yml定义了Serverless应用模型,template.yml的重要字段说明如下:

    ROSTemplateFormatVersion: '2015-09-01'
    Transform: 'Aliyun::Serverless-2018-04-03'
    Resources:
      helloworld:                            # 服务名
        Type: 'Aliyun::Serverless::Service'
        Properties:
          Description: 'helloworld'
        helloworld:                        # 函数名
          Type: 'Aliyun::Serverless::Function'
          Properties:
            Handler: index.handler                        # 事件处理函数
            Runtime: nodejs8                # 运行时,Link IoT Edge支持python3和nodejs8
            CodeUri: 'index.js'                       # 源代码,将会被部署到云

    更多关于template.yml的信息,请参见Serverless Applicaiton Model

  2. 本地测试应用。
    在本地机器上创建完成Serverless应用后,执行如下步骤来测试您的应用。
    1. 执行如下命令启动本地类Link IoT Edge环境。由于类Link IoT Edge环境与正式发布的Link IoT Edge版本使用相同的端口号,启动前请您务必停止正在运行的Link IoT Edge。
      fun edge start
      说明 启动过程中,请根据提示输入网关的设备证书信息。
    2. template.yml文件所在的目录中,执行如下命令,调用并测试helloworld函数。
      fun edge invoke helloworld

      默认情况下,invoke命令从标准输入中,读取事件并调用指定函数。您可以在命令行上直接输入事件内容、按Enter后按Ctrl+D来结束输入。

      您可以通过-e参数指定文件并读取事件。运行成功后将输出函数运行的返回值。

      $ echo "{}" > event.json
      $ fun edge invoke -e event.json hellworld/helloworld
      Using template file at /private/tmp/helloworld/template.yml.
      Invoking function helloworld (nodejs8).
      hello world
  3. 部署应用。
    测试应用没有问题后,可在template.yml文件所在目录中,执行如下命令将应用部署到云端。
    fun deploy
  • 本页导读 (1)