zhangmeng
2023-05-17 37491f4a5d25c506b2e4ff0f9cbbeb4053310cf7
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <string.h>
#include "clib/libnsqclient.h"
 
#include <string>
#include <thread>
#include <mutex>
 
using namespace std;
 
static void produce(int two){
    char ip[] = "192.168.20.108:4150";
    GoString addr = {ip, (ptrdiff_t)strlen(ip)};
    void* p = createProducer(addr);
 
    string msg("cnsqclient dynamic library");
    while(msg.size() < 32){
        msg += msg;
    }
    // printf("msg %s\n", msg.c_str());
 
    for(int i = 0; i < 1000000; i++){
        GoString topic = {"test", 4};
        string amsg = msg + "-x";
        GoSlice data{(void*)amsg.data(), (GoInt)amsg.size(), (GoInt)amsg.size()};
        if (!publish(p, topic, data)){
            printf("publish msg failed topic %s\n", topic.p);
            exit(0);
        }
 
        if (two){
            topic.p = "test2";
            topic.n = 5;
            amsg = msg + "-y";
            data.data = (void*)amsg.data();
            if (!publish(p, topic, data)){
                printf("publish msg failed topic %s\n", topic.p);
                exit(0);
            }
        }
 
    }
    destroyProducer(p);
}
 
 
static void consume(const char* topic, const char* channel){
    GoString t = {topic, (ptrdiff_t)strlen(topic)};
    GoString c = {channel, (ptrdiff_t)strlen(channel)};
 
    void* con = createConsumer(t, c);
 
 
    // thread
    thread([&con]{
 
        // char ip[] = "192.168.20.108:4150";
        // GoString addr = {ip, (ptrdiff_t)strlen(ip)};
        // Run(con, addr);
 
        char lip[] = "192.168.20.108:4161";
        GoString laddr = {lip, (ptrdiff_t)strlen(lip)};
        RunLookupd(con, laddr);
 
    }).detach();
 
    auto start = chrono::steady_clock::now();
    int count = 0;
    while (true) {
        void* msg = NULL;
        size_t size = 0;
        GoUint8 ok = getMessage(con, &msg, &size);
        if (!ok){
            this_thread::sleep_for(chrono::milliseconds(100));
            continue;
        }
        count++;
        printf("======>> recv msg %s size %d\n", (char*)msg, count);
        relMessage(msg);
        if (count > 999000){
            printf("======>> use time %ld\n",
                chrono::duration_cast<chrono::seconds>(chrono::steady_clock::now()-start).count());
        }
    }
    printf("======>> recv all msg size %d\n", count);
}
 
int main(int argc, char const *argv[])
{
    bool two = false;
 
    thread([two]{
        produce(two);
    }).detach();
 
    if (two) thread([]{ consume("test2", "sensor01"); }).detach();
 
    consume("test", "sensor01");
 
    return 0;
}