开发

如何为触发器和函数开发

Redis 开源 Redis Enterprise 软件 Redis Cloud Redis 开源 用于 Kubernetes 的 Redis Enterprise 客户端

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

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

或者您可以手动将其作为 devDependency 添加到您的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[s]://[[username][:password]@][host][:port][/db-number]>

您现在可以运行您的 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);

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

评价此页面
返回顶部 ↑