Redis 压测

最近更新时间:2025-07-28 11:15:02

我的收藏
本文介绍云压测 Redis 测试脚本编写方法,用于支持 Redis 数据库常用操作。

基本用法

使用 Client 概览 API 提供的接口,您可以创建 Redis 数据库的客户端并发送操作请求,进行数据库的基本操作。

数据库连接

建立 Redis 数据库连接可以调用 new redis.Client(url: string) 方法。其中,url 是目标 redis 的地址。
示例如下:
import redis from "pts/redis";

let client = new redis.Client("redis://:<password>@<host>:6379/0");

export default function () {
// ...
}
说明:
建议将上述建立数据库连接的语句,作为全局变量放在主函数外部(如示例),以供同一个 VU 在迭代执行主函数时能够复用连接,避免多次重复创建数据库连接,带来不必要的资源消耗。

数据库操作

连接数据库之后,可以通过 redis 方法进行数据库操作,如下方示例所示。其他方法请参考 JavaScript API 文档 pts/redis
// redis API
import redis from 'pts/redis';

// Create a redis Client instance.
let client = new redis.Client('redis://:<password>@<host>:6379/0');

export default function () {
// set the value of the specified key.
let resp = client.set('key', 'hello, world', 0);
console.log(`redis set ${resp}`); // OK
// obtain the value of the specified key.
let val = client.get('key');
console.log(`redis get ${val}`); // hello, world
// delete an existing key.
let cnt = client.del('key');
console.log(`redis del ${cnt}`); // 1

// insert one or more values at the head of the list.
let lpushResp = client.lPush('list', 'foo');
console.log(`redis lpush ${lpushResp}`); // 1
// remove and obtain the first element of the list.
let lpopResp = client.lPop('list');
console.log(`redis lpop ${lpopResp}`); // foo
// obtain the length of the list.
let listLen = client.lLen('list');
console.log(`redis llen ${listLen}`); // 0

// set the fields and values in the hash table key.
let hashSetResp = client.hSet('myhash', 'k', 1);
console.log(`redis hset ${hashSetResp}`); // 1
// obtain the value stored in the specified field of the hash table.
let hashGetResp = client.hGet('myhash', 'k');
console.log(`redis hget ${hashGetResp}`); // 1
// delete one or more hash table fields.
let hashDelResp = client.hDel('myhash', 'k');
console.log(`redis hdel ${hashDelResp}`); // 1

// add one or more members to the set.
let setAddResp = client.sAdd('set', 'hello');
console.log(`redis sadd ${setAddResp}`); // 1
// randomly remove and return an element in the set.
let setPopResp = client.sPop('set');
console.log(`redis spop ${setPopResp}`); // hello
}

脚本验证

若要验证脚本执行结果,可在正式压测前,先使用 PTS 调试功能,快速验证结果是否符合预期。更多详情,请参见 调试场景