k6 新的扩展参考开发
内容来自官方文档,主要是一个学习
创建项目
go mod init github.com/k6io/xk6-redis
参考代码
需要push github
package redis
import (
"context"
"time"
"github.com/go-redis/redis/v8"
"github.com/loadimpact/k6/js/common"
"github.com/loadimpact/k6/js/modules"
)
// Register the extension on module initialization, available to
// import from JS as "k6/x/redis".
func init() {
modules.Register("k6/x/redis", new(Redis))
}
// Redis is the k6 extension for a Redis client.
type Redis struct{}
// Client is the Redis client wrapper.
type Client struct {
client *redis.Client
}
// XClient represents the Client constructor (i.e. `new redis.Client()`) and
// returns a new Redis client object.
func (r *Redis) Client(ctxPtr *context.Context, opts *redis.Options) interface{} {
rt := common.GetRuntime(*ctxPtr)
return common.Bind(rt, &Client{client: redis.NewClient(opts)}, ctxPtr)
}
// Set the given key with the given value and expiration time.
func (c *Client) Set(key, value string, exp time.Duration) {
c.client.Set(c.client.Context(), key, value, exp)
}
// Get returns the value for the given key.
func (c *Client) Get(key string) (string, error) {
res, err := c.client.Get(c.client.Context(), key).Result()
if err != nil {
return "", err
}
return res, nil
}
构建使用
- 安装xk6
go get -u github.com/k6io/xk6/cmd/xk6
- 构建
xk6 build v0.29.0 --with github.com/k6io/xk6-redis
说明:我们构建的时候也可以指定本地代码位置(类似nginx 模块的构建)
xk6 build v0.29.0 \
--with github.com/k6io/xk6-redis="/absolute/path/to/xk6-redis"
- 使用
test.js
import redis from 'k6/x/redis';
const client = new redis.Client({
addr: 'localhost:6379',
password: '',
db: 0,
});
export default function () {
client.set('mykey', 'myvalue', 0);
console.log(`mykey => ${client.get('mykey')}`);
}
参考资料
https://k6.io/blog/extending-k6-with-xk6#existing-k6-extensions
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2020-01-15 grokdebug 一个方便的grok 调试工具
2019-01-15 src-d engine 强大的git 历史分析工具
2019-01-15 Babelfish 基本试用
2019-01-15 Babelfish 开源通用代码解析服务