码迷,mamicode.com
首页 > 其他好文 > 详细

k6 新的扩展参考开发

时间:2021-01-16 12:05:41      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:represent   cal   amp   ddr   script   extend   app   obj   文档   

内容来自官方文档,主要是一个学习

创建项目

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) XClient(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

k6 新的扩展参考开发

标签:represent   cal   amp   ddr   script   extend   app   obj   文档   

原文地址:https://www.cnblogs.com/rongfengliang/p/14284600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!