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

posted on   荣锋亮  阅读(405)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.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 开源通用代码解析服务

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示