test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package test
  2. import (
  3. "basic.com/aps/nsqclient.git"
  4. "context"
  5. "fmt"
  6. "log"
  7. "time"
  8. )
  9. func produce(two bool) {
  10. p, _ := nsqclient.NewProducer("192.168.20.108:4150")
  11. var str string
  12. for len(str) < 32 {
  13. str += "cnsqclient dynamic library"
  14. }
  15. msgx := []byte(str + "--x")
  16. msgy := []byte(str + "--y")
  17. // count := 0
  18. for i := 0; i < 1000000; i++ {
  19. // if e := p.Publish("test", []byte("x")); e != nil {
  20. if e := p.Publish("test", msgx); e != nil {
  21. log.Fatal("Publish error:" + e.Error())
  22. }
  23. if two {
  24. // if e := p.Publish("test", []byte("y")); e != nil {
  25. if e := p.Publish("test2", msgy); e != nil {
  26. log.Fatal("Publish error:" + e.Error())
  27. }
  28. }
  29. // log.Println("send time ", count)
  30. // count++
  31. }
  32. }
  33. func consume(topic, channel string) {
  34. ctx, cancel := context.WithCancel(context.Background())
  35. if c, e := nsqclient.NewNsqConsumer(ctx, topic, channel); e != nil {
  36. fmt.Println("NewNsqConsumer failed", e)
  37. return
  38. } else {
  39. ch := make(chan struct{})
  40. count := 0
  41. c.AddHandler(func(data []byte) error {
  42. count++
  43. fmt.Println("recv msg ", string(data), " size", count)
  44. if count > 999000 {
  45. ch <- struct{}{}
  46. }
  47. return nil
  48. })
  49. // go c.Run("192.168.20.108:4150", 2)
  50. go c.RunLookupd("192.168.20.108:4161", 2)
  51. t := time.Now()
  52. <-ch
  53. // fmt.Println("======>> use time ", time.Since(t))
  54. fmt.Println("======>> use time ", time.Now().Unix()-t.Unix())
  55. cancel()
  56. }
  57. }
  58. func Test() {
  59. two := false
  60. go produce(two)
  61. if two {
  62. go consume("test2", "sensor01")
  63. }
  64. consume("test", "sensor01")
  65. }