Apache OpenWhisk 中 Node.js 动作开发完全指南

Apache OpenWhisk 中 Node.js 动作开发完全指南

openwhisk Apache OpenWhisk is an open source serverless cloud platform openwhisk 项目地址: https://gitcode.com/gh_mirrors/ope/openwhisk

一、Node.js 动作基础

Apache OpenWhisk 支持使用 JavaScript/Node.js 开发无服务器函数(动作)。Node.js 动作本质上是一个 JavaScript 函数,遵循特定的约定和模式。

1.1 基本动作结构

最简单的 Node.js 动作只需要导出一个 main 函数:

function main() {
    return { msg: 'Hello world' };
}

关键点:

  • main 函数是动作的入口点
  • 可以返回 JSON 对象或数组
  • 参数通过函数参数传递
  • 支持同步和异步执行模式

1.2 创建和调用动作

创建动作的基本命令格式:

wsk action create <动作名称> <js文件>

示例:

wsk action create hello hello.js

调用动作:

wsk action invoke --result hello

二、异步动作开发

Node.js 的异步特性在 OpenWhisk 中通过 Promise 完美支持。

2.1 Promise 基础示例

function main(args) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({ done: true });
        }, 2000);
    });
}

2.2 异步动作特点

  1. 非阻塞执行:动作可以在主函数返回后继续执行
  2. 结果延迟返回:通过 resolve/reject 控制最终输出
  3. 错误处理:使用 reject 处理异常情况
  4. 执行时间统计:系统会准确记录从开始到 resolve 的完整时间

2.3 实际应用场景

  • 调用外部 API 服务
  • 数据库操作
  • 文件系统操作
  • 任何需要等待的操作

三、外部服务集成

OpenWhisk 动作可以方便地集成各种外部服务。下面是一个调用天气 API 的完整示例:

const request = require('request');

function main(params) {
    const location = params.location || '北京';
    const url = `https://api.weather.com/v3/location/search?query=${location}`;
    
    return new Promise((resolve, reject) => {
        request.get(url, (error, response, body) => {
            if (error) {
                reject(error);
            } else {
                const data = JSON.parse(body);
                resolve({
                    location: data.location.name,
                    temperature: data.current.temperature,
                    conditions: data.current.conditions
                });
            }
        });
    });
}

关键点:

  1. 使用 require 引入需要的库
  2. 从参数中获取输入
  3. 返回 Promise 处理异步请求
  4. 正确处理成功和失败情况

四、模块化开发

对于复杂应用,建议使用 Node.js 模块系统组织代码。

4.1 基本模块结构

/my-action
├── package.json
├── index.js
└── node_modules/

package.json 示例:

{
  "name": "my-action",
  "main": "index.js",
  "dependencies": {
    "left-pad": "^1.1.3"
  }
}

index.js 示例:

const leftPad = require('left-pad');

function main(params) {
    const lines = params.lines || [];
    return { 
        padded: lines.map(l => leftPad(l, 30, ".")) 
    };
}

exports.main = main;

4.2 打包和部署

  1. 安装依赖:
npm install
  1. 打包代码:
zip -r action.zip *
  1. 创建动作:
wsk action create my-action --kind nodejs:20 action.zip

五、高级打包技巧

5.1 处理原生依赖

对于包含原生依赖的库,需要特殊处理:

  1. 使用 Docker 容器编译
docker run -it -v $PWD:/nodejsAction openwhisk/action-nodejs-v20 "npm install"
  1. 构建自定义运行时
FROM openwhisk/action-nodejs-v20
RUN npm install <包含原生依赖的库>

5.2 使用打包工具

5.2.1 Rollup.js 配置
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';

export default {
  input: 'index.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [
    resolve(),
    commonjs()
  ]
};
5.2.2 Webpack 配置
module.exports = {
  entry: './index.js',
  target: 'node',
  output: {
    filename: 'bundle.js'
  }
};

六、运行时环境

OpenWhisk 提供两种 Node.js 运行时环境:

6.1 Node.js 18 环境

  • 指定方式:--kind nodejs:18
  • 预装模块:openwhisk SDK

6.2 Node.js 20 环境(默认)

  • 指定方式:--kind nodejs:20
  • 预装模块:openwhisk SDK

七、最佳实践

  1. 错误处理:始终处理可能的错误和异常
  2. 参数验证:验证输入参数的合法性
  3. 资源清理:确保释放所有资源
  4. 日志记录:使用 console.log 记录重要信息
  5. 性能优化:减少冷启动时间
  6. 模块化:合理组织代码结构
  7. 依赖管理:最小化依赖项

通过本文介绍的各种技术和模式,开发者可以充分利用 OpenWhisk 和 Node.js 的强大功能,构建高效、可靠的无服务器应用。

openwhisk Apache OpenWhisk is an open source serverless cloud platform openwhisk 项目地址: https://gitcode.com/gh_mirrors/ope/openwhisk

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冯海莎Eliot

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值