使用k6进行kafka负载测试

1.安装环境

kafka环境

参考Docker搭建kafka环境-CSDN博客

xk6-kafka环境

bash 复制代码
./xk6 build --with github.com/mostafa/xk6-kafka@latest

查看安装情况

2.编写脚本

test_kafka.js

javascript 复制代码
// Either import the module object
import * as kafka from "k6/x/kafka";

// Or individual classes and constants
import {
    Writer,
    Reader,
    Connection,
    SchemaRegistry,
    SCHEMA_TYPE_STRING,
} from "k6/x/kafka";

// Creates a new Writer object to produce messages to Kafka
const writer = new Writer({
    // WriterConfig object
    brokers: ["localhost:9092"],
    topic: "my-topic",
});

const reader = new Reader({
    // ReaderConfig object
    brokers: ["localhost:9092"],
    topic: "my-topic",
});

const connection = new Connection({
    // ConnectionConfig object
    address: "localhost:9092",
});

const schemaRegistry = new SchemaRegistry();
// Can accept a SchemaRegistryConfig object

if (__VU == 0) {
    // Create a topic on initialization (before producing messages)
    connection.createTopic({
    // TopicConfig object
    topic: "my-topic",
    });
}

export default function () {
    // Fetch the list of all topics
    const topics = connection.listTopics();
    console.log(topics); // list of topics

    // Produces message to Kafka
    writer.produce({
    // ProduceConfig object
    messages: [
        // Message object(s)
        {
        key: schemaRegistry.serialize({
            data: "my-key",
            schemaType: SCHEMA_TYPE_STRING,
        }),
        value: schemaRegistry.serialize({
            data: "my-value",
            schemaType: SCHEMA_TYPE_STRING,
        }),
        },
    ],
    });

    // Consume messages from Kafka
    let messages = reader.consume({
    // ConsumeConfig object
    limit: 10,
    });

    // your messages
    console.log(messages);

    // You can use checks to verify the contents,
    // length and other properties of the message(s)

    // To serialize the data back into a string, you should use
    // the deserialize method of the Schema Registry client. You
    // can use it inside a check, as shown in the example scripts.
    let deserializedValue = schemaRegistry.deserialize({
    data: messages[0].value,
    schemaType: SCHEMA_TYPE_STRING,
    });
}

export function teardown(data) {
    // Delete the topic
    connection.deleteTopic("my-topic");

    // Close all connections
    writer.close();
    reader.close();
    connection.close();
}

3.运行测试

运作之前先开启kafka服务,打开终端输入命令

bash 复制代码
./k6 run test_kafka.js --vus 50 --duration 10s

测试结果

相关推荐
<e^πi+1=0>42 分钟前
Docker搭建kafka环境
docker·kafka
爱吃香蕉的猴哥1 小时前
消息系统之 Kafka
分布式·kafka
逸曦玥泱3 小时前
搭建分布式Kafka集群
分布式·kafka
许墨の小蝴蝶3 小时前
Python发送带key的kafka消息
python·kafka
编程、小哥哥3 小时前
在 DDD 中优雅的发送 Kafka 消息
分布式·kafka
core5123 小时前
flink实现复杂kafka数据读取
大数据·flink·kafka·cdc
I nedd more power3 小时前
Kafka 磁道寻址过程详解
分布式·kafka
伟伟哦3 小时前
kafka的处理的一些问题 消费延迟
分布式·kafka
AutoMQ3 小时前
Kafka 迁移 AutoMQ 时 Flink 位点管理的挑战与解决方案
大数据·阿里云·云原生·kafka·云计算·腾讯云·aws·消息·gcp·计算·automq