开发

如何开发触发器和函数

为了帮助开发新的触发器和函数库,您可以使用触发器和函数API的类型声明文件,这允许您首选的开发环境提供自动完成和类型检查。您可以使用以下命令安装此信息:

npm install https://gitpkg.now.sh/RedisGears/RedisGears/js_api --save-dev

或者你可以手动将其作为开发依赖项添加到你的 package.json 文件中:

"devDependencies": {
  "@redis/gears-api": "https://gitpkg.now.sh/RedisGears/RedisGears/js_api"
}

示例项目设置

为你的新触发器和函数项目创建一个空目录,my_first_project。导航到该文件夹并运行以下命令:

$ npm init -y -f
npm WARN using --force Recommended protections disabled.
Wrote to /home/work/my_first_project/package.json:

{
  "name": "my_first_project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

更新package.json以将gears API添加到devDependencies对象中。

{
  "name": "my_first_project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "@redis/gears-api": "https://gitpkg.now.sh/RedisGears/RedisGears/js_api"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

使用npm install安装依赖项。

创建一个新文件,index.js 并导入 gears-api 模块。虽然这一步不是严格必要的,但这样做可以在添加 registerFunction 时启用智能代码补全:

#!js name=lib api_version=1.0

import { redis } from '@redis/gears-api';

redis.registerFunction("test", ()=>{
    return "test";
});

为了自动化部署,请更新package.json中的scripts部分:

"scripts": {
  "deploy": "gears-api index.js"
}

现在你可以使用以下命令将你的代码部署到 Redis Stack:

> npm run deploy -- -r redis://localhost:6379

> deploy
> gears-api index.js

Deployed! :)

提供的URL应遵循以下格式:

您现在可以运行您的 Redis Stack 函数:

127.0.0.1:6379> TFCALL lib.test 0
"test"

使用第三方npm包的示例函数

如果你想在Redis Stack函数中使用第三方的npm包,整个过程与之前讨论的几乎相同,只有一些差异。

首先,您需要使用npm install安装您的包。在这个例子中,math.js库中的pi符号将用于一个计算圆面积的简单函数。

npm install mathjs

注意:你的 package.json 文件也会随着新的依赖项更新。例如:

"dependencies": {
    "mathjs": "^12.0.0"
}

接下来,您将把所需的符号导入到您的函数中。

#!js api_version=1.0 name=lib

import { redis } from '@redis/gears-api';
import { pi } from 'mathjs';

function calculateCircleArea(client, radius) {
  return pi * radius * radius;
}

redis.registerFunction('calculateArea', calculateCircleArea);

按照前一节中的描述加载并运行您的新函数。

RATE THIS PAGE
Back to top ↑