本文介绍云压测 Redis 测试脚本编写方法,用于支持 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 APIimport 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}