本示例为函数计算的入门教程,介绍使用函数计算编写 Hello World 的步骤。
简介
有四种方式创建函数:使用控制台、使用命令行工具 Fun、使用命令行工具 fcli、使用 SDK。正如文章 函数计算使用流程 所介绍,使用函数计算的步骤为:新建服务 -> 新建函数 -> 执行函数
- 使用控制台编写函数(推荐)
- 使用 Fun 创建函数(推荐)
- 使用 fcli 创建函数
- 使用 SDK 创建函数
使用控制台编写函数(推荐)
参考文章 使用控制台,按照 新建服务 -> 新建函数 -> 执行函数 的步骤介绍。
- 新建服务,服务名为 demo(您可以设置自己的服务名)。
- 配置日志项目 LogProject 和日志仓库 logStore ,该服务下函数的日志会打到日志仓库中,有关日志的更多信息,请参考 函数日志。
- 角色创建方式选择 新建角色 -> 点击授权,系统会创建一个拥有访问日志服务权限的角色。
- 新建函数
- 触发器配置:不创建触发器。
- 所在服务:demo。
- 函数名称:testHelloWorld (您可以设置自己的函数名)。
- 运行环境根据您熟悉的语言选择
- 如果您选择的语言是 java,请参考文章 Java runtime 。控制台不支持 java 函数的在线编辑,需要您打成 jar 包上传至控制台。
- 环境变量无需设置。
- 函数入口根据提示填写。
- 函数执行内存为为此函数分配的内存大小,默认为 512 M,最大为 3072 M,如果您需要更大内存可以 联系我们。
- 超时时间为函数执行的最大时间,函数运行超过这个时间会强制结束。
- 如果需要使用 initializer 功能,可以通过可选开关进行配置。
- 跳过权限配置过程。
- 完成函数创建过程。
在代码编辑页面输入默认的 Hello World 函数(控制台编辑器的默认函数就是 Hello World 函数),点击执行,在控制台可以看到执行结果和执行日志。
函数计算控制台只可以执行函数和查看当前的执行信息,您可以在日志服务控制台 查看函数的历史执行日志。有关更多信息,请参考 函数日志。
使用 Fun 创建函数(推荐)
如果本地没有安装过 Fun,请按照 教程 安装 Fun。
安装完成后,我们首先使用 fun init 功能,根据模板初始化示例项目。
直接输入 fun init -n demo
,fun 会提示选择一个模板进行初始化。选择相应的模板即可。
$ fun init -n demo
? Select a template to init (Use arrow keys or type to search)
❯ helloworld-nodejs8
helloworld-nodejs6
helloworld-python3
helloworld-python2.7
helloworld-java8
helloworld-php7.2
比如,如果选择 helloworld-nodejs8 这个模板,会显示如下信息:
Start rendering template...
+ /Users/tan/demo
+ /Users/tan/demo/index.js
+ /Users/tan/demo/template.yml
finish rendering template.
可以看到,fun 在我们执行命令的目录(/Users/tan)下,创建了一个 demo 的目录,并添加了两个文件,一个是 index.js,一个是 template.yml。
index.js 就是包含了函数的示例代码,而 template.yml 会告诉 Fun 如何创建函数资源。template.yml 文件支持的配置项 请参考。
初始化完成后,可以直接执行 fun deploy
将本地函数资源部署到远端。执行 fun deploy 后,得到如下输出:
$ fun deploy
using region: cn-hangzhou
using accountId: ***********3557
using accessKeyId: ***********r3Ra
using timeout: 300
Waiting for service demo to be deployed...
Waiting for function demo to be deployed...
Waiting for packaging function demo code...
package function demo code done
function demo deploy success
service demo deploy success
登陆,控制台,可以看到我们的 demo 服务,以及 demo 函数已经被创建成功了。如果您的本地有 dokcer(注意:windows 需要安装 Docker for windows,请参考),还可以直接执行 fun local invoke
在本地模拟运行、调试函数。
下面是一个模拟运行的输出:
$ fun local invoke demo
skip pulling image aliyunfc/runtime-nodejs8:1.5.3...
FC Invoke Start RequestId: ae23edf8-fec6-47d0-a9a5-82744726f5f5
load code for handler:index.handler
2019-06-21T06:00:43.788Z ae23edf8-fec6-47d0-a9a5-82744726f5f5 [verbose] hello world
FC Invoke End RequestId: ae23edf8-fec6-47d0-a9a5-82744726f5f5
hello world
RequestId: ae23edf8-fec6-47d0-a9a5-82744726f5f5 Billed Duration: 122 ms Memory Size: 1998 MB Max Memory Used: 61 MB
更多本地单步调试、运行函数的方法,请参考 开发函数计算的正确姿势 —— 使用 Fun Local 本地运行与调试。
Fun 的更多教程 请参考 。
使用 fcli 创建函数
准备工作
下载函数计算命令行工具 fcli ,执行 fcli shell
进入交互模式。有关 fcli 的更多信息请参考 fcli。
如果您是第一次使用 fcli,请按提示配置 endpoint,access key id / secret 等信息。
- 如果下载fcli工具遇到网络卡顿情况,可以点击这里下载: linux; mac; windows.
编写代码
在当前目录下创建名为 code 的目录,在 code 目录下创建 hello_world.js 文件(或 hello_world.py, 后面 python 版本示例都是同名的规则,之后不再赘述),实现名为 handler 的 nodejs 事件处理函数。
.mytabs {
width: 100%;
max-width: 900px;
height: 580px;
margin: 10px auto;
background: #CCC;
}
.ls_label {
cursor: pointer;
background: -webkit-linear-gradient(#BBB, #AAA);
color: #eee;
border-radius: 5px 5px 0 0;
padding: 1.5% 1.5%;
float: left;
margin-right: 2px;
font: italic 1em cambria;
margin-top:5px;
}
.ls_margin1 {
margin-left:3%;
}
.ls_margin2 {
margin-left:0.2%;
}
.ls_margin3 {
margin-left:0.2%;
}
.ls_margin4 {
margin-left:0.2%;
}
input:checked + label {
background: #fff;
color: #999;
}
.mytabs input:nth-of-type(1):checked ~ .panels .panel:first-child,
.mytabs input:nth-of-type(2):checked ~ .panels .panel:nth-child(2),
.mytabs input:nth-of-type(3):checked ~ .panels .panel:nth-child(3),
.mytabs input:nth-of-type(4):checked ~ .panels .panel:last-child{
opacity: 1;
-webkit-transition: .3s;
z-index : 1;
}
.panels {
float: left;
clear: both;
position: relative;
width: 90%;
border-radius: 0 10px 10px 10px;
min-height: 520px;
font-family: Cambria, Arial;
background: #fff;
margin-left:3%;
}
.panel {
width: 90%;
position: absolute;
opacity: 0;
background: #fff;
border-radius: 0 10px 10px 10px;
padding: 2%;
box-sizing: border-box;
min-height: 500px;
margin-left:3%;
}
'use strict';
module.exports.handler = function(event, context, callback) {
console.log('hello world');
callback(null, 'hello world');
};
# -*- coding: utf-8 -*-
def handler(event, context):
print "hello world"
return 'hello world'
<?php
function handler($event, $context) {
$logger = $GLOBALS['fcLogger'];
$logger->info("hello world");
return "hello world";
}
package example;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class HelloFC implements StreamRequestHandler {
@Override
public void handleRequest(
InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
outputStream.write(new String("hello world").getBytes());
}
}'
// pom.xml
<dependency>
<groupId>com.aliyun.fc.runtime</groupId>
<artifactId>fc-java-core</artifactId>
<version>1.0.0</version>
</dependency>
Nodejs 的函数签名为
function(event, context, callback)
。用户通过调用callback
返回结果。有关更多信息请参考 Nodejs Runtime。Python 的函数签名为
def handler(event, context)
,有关更多信息请参考 Python Runtime。Php 的函数签名为
function handler($event, $context)
,有关更多信息请参考 PHP Runtime。使用 Java 时需要将函数和依赖打成 Jar 包上传,更多信息请参考 Java Runtime。
新建服务
在 fcli shell 中
>>> mks demo # 创建名为 demo 的服务
>>> cd demo # 进入 demo 服务内
新建函数
# Nodejs 版
>>> mkf testHelloWorld -h hello_world.handler -d code -t nodejs6
# Python 版
>>> mkf testHelloWorld -h hello_world.handler -d code -t python2.7
# Php 版
>>> mkf testHelloWorld -h hello_world.handler -d code -t php7.2
# Java 版
>>> mkf testHelloWorld -h example.HelloFC::handleRequest -d code -t java8
参数详解
-
-h
指定事件处理函数,即指定 handler- 对于 Python、Nodejs和Php,handler 格式为
{file}.{method}
。例如hello_world.handler
指定了函数的调用入口为 hello_world.js 文件中的 handler 函数 - 对于 Java,handler 格式为
{package}.{class}::{method}
。例如包名是 example,类名是 HelloFC,那么创建函数时指定的 Handler 为example.HelloFC::handleRequest
- 对于 Python、Nodejs和Php,handler 格式为
-
-d
指定文件所在目录。-d code
告诉 fcli 将当前目录下名为 code 的目录下的文件作为代码文件。fcli 将为您打包代码并上传到函数计算服务。- 代码打包要求您的机器上已安装 docker。docker 的具体安装步骤,请参阅 相关文档 。
- 国内用户访问 docker 官方镜像库速度较慢,建议您使用阿里云镜像加速服务,具体设置请参阅 相关文档 。
- 在 linux 下使用 docker,要求有 root 权限。所以您需要使用
sudo fcli shell
的方式启动命令行工具;或者您可以参照 相关文档 设置,以非 root 用户管理 docker。 - 此外,您也可以将代码存放在 OSS 中,指定 OSS 路径并授予函数计算访问该 OSS 位置的权限。
-
-t
指定了函数的运行环境。目前我们支持 nodejs, python, php 和 java- 有关运行环境的详细信息请参考 Nodejs Runtime,Python Runtime,Java Runtime
-
您还可以通过
-m
参数指定函数运行的内存资源规格,默认为 512 MB -
更多参数请参考:
mkf --help
执行函数
invk testHelloWorld
可以看到执行结果为 hello world
查看日志
首先为服务新建日志项目和日志库。为函数配置日志相关内容请参考 函数日志。
mkl -p my-log-project -s my-log-store myService
// 注意: log project的名字是全局唯一的,如果此名字被其他人占有了,那么会创建失败
logs testHelloWorld
logs
命令可以查看函数历史执行日志,不单可以查看本次执行日志。
使用 SDK 创建函数
当前目录下,有一个 code 文件夹,code 文件夹中有函数文件 index.js 文件,文件的内容是 hello world 代码 。将 code 文件夹打成 zip 包 code.zip。下面对使用 SDK 创建函数并触发函数执行过程进行介绍。有关各个 SDK 的详细信息请参考
- Python SDK
- Nodejs SDK
- Java SDK
Python SDK 创建函数并且调用函数执行:
import fc2
client = fc2.Client(
endpoint='<Your Endpoint>',
accessKeyID='<Your AccessKeyID>',
accessKeySecret='<Your AccessKeySecret>')
# Create service.
client.create_service('demo')
# Create function.
client.create_function('demo', 'testHelloWorld', 'nodejs6', 'hello_world.handler', codeDir = 'code')
# Invoke function synchronously.
client.invoke_function('demo', 'testHelloWorld')
Nodejs SDK 创建函数并且调用函数执行:
'use strict';
var FCClient = require('@alicloud/fc2');
var fs = require('fs');
var client = new FCClient('<account id>', {
accessKeyID: '<access key id>',
accessKeySecret: '<access key secret>',
region: 'cn-shanghai',
timeout: 10000 // Request timeout in milliseconds, default is 10s
});
var serviceName = '<service name>';
var funcName = '<function name>';
client.createService(serviceName).then(function(resp) {
console.log('create service: %j', resp);
return client.createFunction(serviceName, {
functionName: funcName,
handler: 'code/index.handler',
memorySize: 128,
runtime: 'nodejs6',
code: {
zipFile: fs.readFileSync('/tmp/code.zip', 'base64'),
},
});
}).then(function(resp) {
console.log('create function: %j', resp);
return client.invokeFunction(serviceName, funcName);
}).then(function(resp) {
console.log('invoke function: %j', resp);
}).catch(function(err) {
console.error(err);
});
Java SDK 创建函数并且调用函数执行:
import com.aliyuncs.fc.client.FunctionComputeClient;
import com.aliyuncs.fc.model.Code;
import com.aliyuncs.fc.request.*;
import com.aliyuncs.fc.response.*;
import java.io.IOException;
public class testJavaSDK {
private static final String CODE_DIR = "../code";
private static final String REGION = "cn-shanghai";
private static final String SERVICE_NAME = "demo";
private static final String FUNCTION_NAME = "testHelloWorld";
public static void main(final String[] args) throws IOException {
String accountId = "<account id>";
String accessKey = "<access key id>";
String accessSecretKey = "<access key secret>";
// Initialize FC client
FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey);
// Set to a specific endpoint in case needed, endpoint sample: http://123456.cn-hangzhou.fc.aliyuncs.com
// fcClient.setEndpoint("http://{accountId}.{regionId}.fc.aliyuncs.com.");
// Create a service
CreateServiceRequest csReq = new CreateServiceRequest();
csReq.setServiceName(SERVICE_NAME);
csReq.setDescription("FC test service");
CreateServiceResponse csResp = fcClient.createService(csReq);
System.out.println("Created service, request ID " + csResp.getRequestId());
// Create a function
CreateFunctionRequest cfReq = new CreateFunctionRequest(SERVICE_NAME);
cfReq.setFunctionName(FUNCTION_NAME);
cfReq.setDescription("Function for test");
cfReq.setMemorySize(128);
cfReq.setHandler("index.handler");
cfReq.setRuntime("nodejs6");
Code code = new Code().setDir(CODE_DIR);
cfReq.setCode(code);
cfReq.setTimeout(10);
CreateFunctionResponse cfResp = fcClient.createFunction(cfReq);
System.out.println("Created function, request ID " + cfResp.getRequestId());
// Invoke the function with a string as function event parameter, Sync mode
InvokeFunctionRequest invkReq = new InvokeFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
InvokeFunctionResponse invkResp = fcClient.invokeFunction(invkReq);
System.out.println(new String(invkResp.getContent()));
}
}
// pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>testSDK</groupId>
<artifactId>testSDK</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-fc</artifactId>
<version>1.1.8</version>
</dependency>
</dependencies>
</project>
原创文章,作者:网友投稿,如若转载,请注明出处:https://www.cloudads.cn/archives/33408.html