github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/broker/consumer/consumer.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/micro/go-micro/v2/broker"
     8  	"github.com/micro/go-micro/v2/config/cmd"
     9  	// To enable rabbitmq plugin uncomment
    10  	//_ "github.com/micro/go-plugins/broker/rabbitmq"
    11  )
    12  
    13  var (
    14  	topic = "go.micro.topic.foo"
    15  )
    16  
    17  // Example of a shared subscription which receives a subset of messages
    18  func sharedSub() {
    19  	_, err := broker.Subscribe(topic, func(p broker.Event) error {
    20  		fmt.Println("[sub] received message:", string(p.Message().Body), "header", p.Message().Header)
    21  		return nil
    22  	}, broker.Queue("consumer"))
    23  	if err != nil {
    24  		fmt.Println(err)
    25  	}
    26  }
    27  
    28  // Example of a subscription which receives all the messages
    29  func sub() {
    30  	_, err := broker.Subscribe(topic, func(p broker.Event) error {
    31  		fmt.Println("[sub] received message:", string(p.Message().Body), "header", p.Message().Header)
    32  		return nil
    33  	})
    34  	if err != nil {
    35  		fmt.Println(err)
    36  	}
    37  }
    38  
    39  func main() {
    40  	cmd.Init()
    41  
    42  	if err := broker.Init(); err != nil {
    43  		log.Fatalf("Broker Init error: %v", err)
    44  	}
    45  	if err := broker.Connect(); err != nil {
    46  		log.Fatalf("Broker Connect error: %v", err)
    47  	}
    48  
    49  	sub()
    50  	select {}
    51  }