github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/client/mq/kafka/producer/example_produce_test.go (about) 1 package producer 2 3 import ( 4 "fmt" 5 "github.com/Shopify/sarama" 6 "strings" 7 "sync" 8 "time" 9 ) 10 11 func ExampleSend() { 12 cf := sarama.NewConfig() 13 cf.Producer.RequiredAcks = sarama.WaitForAll 14 cf.Producer.Return.Successes = true 15 //cf.Producer.Flush.Frequency = 300 * time.Millisecond 16 17 bList := strings.Split("127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094", ",") 18 p, err := sarama.NewSyncProducer(bList, cf) 19 if err != nil { 20 println("new err", err.Error()) 21 return 22 } 23 24 for i := 0; i < 500; i++ { 25 partition, offset, err := p.SendMessage(&sarama.ProducerMessage{ 26 Topic: "sarama", 27 Value: sarama.StringEncoder(fmt.Sprintf("hi:%d", i)), 28 }) 29 if err != nil { 30 println("send err", err.Error()) 31 return 32 } 33 println(partition, offset) 34 } 35 36 err = p.Close() 37 if err != nil { 38 println("close err", err.Error()) 39 return 40 } 41 42 // Output: 43 // 44 } 45 46 func ExampleProducer_SyncProducerOps() { 47 p := NewProducer("sarama", "sync", nil, 48 WithVersion("2.8.0"), 49 WithClientID("producer.test"), 50 WithBrokerList("127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094"), 51 WithRequiredAcks(-1), 52 WithRetryMaxCn(3), 53 WithCompression(""), 54 WithPartitioning(""), 55 ) 56 defer p.Close() 57 58 t := time.NewTimer(3 * time.Second) 59 cn := 0 60 wg := &sync.WaitGroup{} 61 wg.Add(1) 62 go func() { 63 defer wg.Done() 64 for { 65 select { 66 case <-t.C: 67 println("send over, send totalCn:", cn) 68 return 69 default: 70 p.Send(fmt.Sprintf("hi:%d", cn)) 71 cn++ 72 //time.Sleep(100 * time.Millisecond) 73 } 74 } 75 }() 76 wg.Wait() 77 78 // Output: 79 // 80 } 81 82 func ExampleProducer_ASyncProducerOps() { 83 p := NewProducer("test", "async", nil, 84 WithVersion("2.8.0"), 85 WithClientID("producer.test"), 86 WithBrokerList("127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094"), 87 WithRequiredAcks(-1), 88 WithRetryMaxCn(3), 89 WithCompression(""), 90 WithPartitioning(""), 91 ) 92 defer p.Close() 93 94 t := time.NewTimer(3 * time.Second) 95 cn := 0 96 wg := &sync.WaitGroup{} 97 wg.Add(1) 98 go func() { 99 defer wg.Done() 100 for { 101 select { 102 case <-t.C: 103 println("send over, send totalCn:", cn) 104 return 105 default: 106 p.Send(fmt.Sprintf("hi:%d", cn+100)) 107 cn++ 108 //time.Sleep(100 * time.Millisecond) 109 } 110 } 111 }() 112 wg.Wait() 113 114 // Output: 115 // 116 }