azure-event-hubs-go/_examples/helloworld
Joel Hendrix 8a67a58a98
Update to latest go-amqp and common module (#281)
* Update to latest go-amqp and common module

* fix detection of closed links

* clean up lint

* cleanup

* make detach errors recoverable

* update to latest common and tagged go-amqp
2022-12-06 11:03:37 -08:00
..
consumer Update to latest go-amqp and common module (#281) 2022-12-06 11:03:37 -08:00
producer Update to latest go-amqp and common module (#281) 2022-12-06 11:03:37 -08:00
.gitignore add an example 2018-02-15 14:40:17 -08:00
Makefile refactored token providers and cbs 2018-02-16 15:59:00 -08:00
readme.md add a readme for the example 2018-02-15 14:49:10 -08:00

readme.md

Hello World Producer / Consumer

This example illustrates a producer sending message round-robbin into an Event Hub instance. The consumer receives from each Event Hub partition, and outputs the message it receives. Upon entering 'exit' into the producer, the producer will send, then exit, and the receiver will receive the message and close.

To Run

  • from this directory execute make
  • open two terminal windows
    • in the first terminal, execute ./bin/consumer
    • in the second terminal, execute ./bin/producer
    • in the second terminal, type some works and press enter
  • see the words you typed in the second terminal in the first
  • type 'exit' in the second terminal when you'd like to end your session

Producer

func main() {
	hub, _ := initHub()

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Enter text: ")
		text, _ := reader.ReadString('\n')
		hub.Send(context.Background(), &amqp.Message{Data: []byte(text)})
		if text == "exit\n" {
			break
		}
	}
}

Consumer

func main() {
	hub, partitions := initHub()
	exit := make(chan struct{})

	handler := func(ctx context.Context, msg *amqp.Message) error {
		text := string(msg.Data)
		if text == "exit\n" {
			fmt.Println("Someone told me to exit!")
			exit <- *new(struct{})
		} else {
			fmt.Println(string(msg.Data))
		}
		return nil
	}

	for _, partitionID := range *partitions {
		hub.Receive(partitionID, handler)
	}

	select {
	case <-exit:
		fmt.Println("closing after 2 seconds")
		select {
		case <-time.After(2 * time.Second):
			return
		}
	}
}