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