ctest.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "clib/libnsqclient.h"
  4. #include <string>
  5. #include <thread>
  6. #include <mutex>
  7. using namespace std;
  8. static void produce(int two){
  9. char ip[] = "192.168.20.108:4150";
  10. GoString addr = {ip, (ptrdiff_t)strlen(ip)};
  11. void* p = createProducer(addr);
  12. string msg("cnsqclient dynamic library");
  13. while(msg.size() < 32){
  14. msg += msg;
  15. }
  16. // printf("msg %s\n", msg.c_str());
  17. for(int i = 0; i < 1000000; i++){
  18. GoString topic = {"test", 4};
  19. string amsg = msg + "-x";
  20. GoSlice data{(void*)amsg.data(), (GoInt)amsg.size(), (GoInt)amsg.size()};
  21. if (!publish(p, topic, data)){
  22. printf("publish msg failed topic %s\n", topic.p);
  23. exit(0);
  24. }
  25. if (two){
  26. topic.p = "test2";
  27. topic.n = 5;
  28. amsg = msg + "-y";
  29. data.data = (void*)amsg.data();
  30. if (!publish(p, topic, data)){
  31. printf("publish msg failed topic %s\n", topic.p);
  32. exit(0);
  33. }
  34. }
  35. }
  36. destroyProducer(p);
  37. }
  38. static void consume(const char* topic, const char* channel){
  39. GoString t = {topic, (ptrdiff_t)strlen(topic)};
  40. GoString c = {channel, (ptrdiff_t)strlen(channel)};
  41. void* con = createConsumer(t, c);
  42. // thread
  43. thread([&con]{
  44. // char ip[] = "192.168.20.108:4150";
  45. // GoString addr = {ip, (ptrdiff_t)strlen(ip)};
  46. // Run(con, addr);
  47. char lip[] = "192.168.20.108:4161";
  48. GoString laddr = {lip, (ptrdiff_t)strlen(lip)};
  49. RunLookupd(con, laddr);
  50. }).detach();
  51. auto start = chrono::steady_clock::now();
  52. int count = 0;
  53. while (true) {
  54. void* msg = NULL;
  55. size_t size = 0;
  56. GoUint8 ok = getMessage(con, &msg, &size);
  57. if (!ok){
  58. this_thread::sleep_for(chrono::milliseconds(100));
  59. continue;
  60. }
  61. count++;
  62. printf("======>> recv msg %s size %d\n", (char*)msg, count);
  63. relMessage(msg);
  64. if (count > 999000){
  65. printf("======>> use time %ld\n",
  66. chrono::duration_cast<chrono::seconds>(chrono::steady_clock::now()-start).count());
  67. }
  68. }
  69. printf("======>> recv all msg size %d\n", count);
  70. }
  71. int main(int argc, char const *argv[])
  72. {
  73. bool two = false;
  74. thread([two]{
  75. produce(two);
  76. }).detach();
  77. if (two) thread([]{ consume("test2", "sensor01"); }).detach();
  78. consume("test", "sensor01");
  79. return 0;
  80. }