producer_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package sarama
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "testing"
  6. )
  7. func TestSimpleProducer(t *testing.T) {
  8. responses := make(chan []byte, 1)
  9. extraResponses := make(chan []byte)
  10. mockBroker := NewMockBroker(t, responses)
  11. mockExtra := NewMockBroker(t, extraResponses)
  12. defer mockBroker.Close()
  13. defer mockExtra.Close()
  14. // return the extra mock as another available broker
  15. response := []byte{
  16. 0x00, 0x00, 0x00, 0x01,
  17. 0x00, 0x00, 0x00, 0x01,
  18. 0x00, 0x09, 'l', 'o', 'c', 'a', 'l', 'h', 'o', 's', 't',
  19. 0x00, 0x00, 0x00, 0x00,
  20. 0x00, 0x00, 0x00, 0x01,
  21. 0x00, 0x00,
  22. 0x00, 0x08, 'm', 'y', '_', 't', 'o', 'p', 'i', 'c',
  23. 0x00, 0x00, 0x00, 0x01,
  24. 0x00, 0x00,
  25. 0x00, 0x00, 0x00, 0x00,
  26. 0x00, 0x00, 0x00, 0x01,
  27. 0x00, 0x00, 0x00, 0x00,
  28. 0x00, 0x00, 0x00, 0x00}
  29. binary.BigEndian.PutUint32(response[19:], uint32(mockExtra.Port()))
  30. responses <- response
  31. go func() {
  32. for i := 0; i < 10; i++ {
  33. msg := []byte{
  34. 0x00, 0x00, 0x00, 0x01,
  35. 0x00, 0x08, 'm', 'y', '_', 't', 'o', 'p', 'i', 'c',
  36. 0x00, 0x00, 0x00, 0x01,
  37. 0x00, 0x00, 0x00, 0x00,
  38. 0x00, 0x00,
  39. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
  40. binary.BigEndian.PutUint64(msg[23:], uint64(i))
  41. extraResponses <- msg
  42. }
  43. }()
  44. client, err := NewClient("client_id", []string{mockBroker.Addr()}, nil)
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. defer client.Close()
  49. producer, err := NewProducer(client, "my_topic", &ProducerConfig{RequiredAcks: WaitForLocal})
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. defer producer.Close()
  54. for i := 0; i < 10; i++ {
  55. err = producer.SendMessage(nil, StringEncoder("ABC THE MESSAGE"))
  56. if err != nil {
  57. t.Error(err)
  58. }
  59. }
  60. }
  61. func ExampleProducer() {
  62. client, err := NewClient("my_client", []string{"localhost:9092"}, nil)
  63. if err != nil {
  64. panic(err)
  65. } else {
  66. fmt.Println("> connected")
  67. }
  68. defer client.Close()
  69. producer, err := NewProducer(client, "my_topic", &ProducerConfig{RequiredAcks: WaitForLocal})
  70. if err != nil {
  71. panic(err)
  72. }
  73. defer producer.Close()
  74. err = producer.SendMessage(nil, StringEncoder("testing 123"))
  75. if err != nil {
  76. panic(err)
  77. } else {
  78. fmt.Println("> message sent")
  79. }
  80. }