subscribe_demo.js 1.2 KB
Newer Older
1
const taos = require("@tdengine/client");
2 3

const conn = taos.connect({ host: "localhost", database: "power" });
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
var cursor = conn.cursor();

function runConsumer() {

    // create topic 
    cursor.execute("create topic topic_name_example as select * from meters");

    let consumer = taos.consumer({
        'group.id': 'tg2',
        'td.connect.user': 'root',
        'td.connect.pass': 'taosdata',
        'msg.with.table.name': 'true',
        'enable.auto.commit': 'true'
    });
    
    // subscribe the topic just created.
    consumer.subscribe("topic_name_example");

    // get subscribe topic list
    let topicList = consumer.subscription();
    console.log(topicList);

    for (let i = 0; i < 5; i++) {
        let msg = consumer.consume(100);
        console.log(msg.topicPartition);
        console.log(msg.block);
        console.log(msg.fields)
31
        consumer.commit(msg);
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        console.log(`=======consumer ${i} done`)
    }

    consumer.unsubscribe();
    consumer.close();

    // drop topic
    cursor.execute("drop topic topic_name_example");
}


try {
    runConsumer();
} finally {

    setTimeout(() => {
        cursor.close();
        conn.close();
    }, 2000);
H
Huo Linhe 已提交
51
}