github.com/moleculer-go/moleculer@v0.3.3/examples/amqp_transporter/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/moleculer-go/moleculer"
     6  	"github.com/moleculer-go/moleculer/broker"
     7  	"github.com/moleculer-go/moleculer/payload"
     8  	"github.com/moleculer-go/moleculer/strategy"
     9  	"github.com/moleculer-go/moleculer/transit/amqp"
    10  	log "github.com/sirupsen/logrus"
    11  	"math/rand"
    12  	"os"
    13  	"sync"
    14  	"time"
    15  )
    16  
    17  var mathService = moleculer.ServiceSchema{
    18  	Name: "math",
    19  	Actions: []moleculer.Action{
    20  		{
    21  			Name: "add",
    22  			Handler: func(ctx moleculer.Context, params moleculer.Payload) interface{} {
    23  				return params.Get("a").Int() + params.Get("b").Int()
    24  			},
    25  		},
    26  	},
    27  }
    28  
    29  func main() {
    30  	url := os.Getenv("AMQP_HOST")
    31  	if url == "" {
    32  		url = "guest:guest@localhost"
    33  	}
    34  
    35  	amqpConfig := amqp.AmqpOptions{
    36  		Url:              []string{"amqp://" + url + ":5672"},
    37  		AutoDeleteQueues: 20 * time.Second,
    38  		ExchangeOptions: map[string]interface{}{
    39  			"durable": true,
    40  		},
    41  		QueueOptions: map[string]interface{}{
    42  			"durable": true,
    43  		},
    44  		Logger: log.WithField("transport", "amqp"),
    45  	}
    46  
    47  	config := moleculer.Config{
    48  		LogLevel: "debug",
    49  		TransporterFactory: func() interface{} {
    50  			return amqp.CreateAmqpTransporter(amqpConfig)
    51  		},
    52  		StrategyFactory: func() interface{} {
    53  			return strategy.NewRoundRobinStrategy()
    54  		},
    55  	}
    56  
    57  	bkrServer := broker.New(&config)
    58  	bkrServer.Publish(mathService)
    59  	bkrServer.Start()
    60  
    61  	wg := sync.WaitGroup{}
    62  	wg.Add(1)
    63  
    64  	bkrClient := broker.New(&config)
    65  	bkrClient.LocalBus().Once("$registry.service.added", func(value ...interface{}) {
    66  		if value[0].(map[string]string)["name"] != "math" {
    67  			return
    68  		}
    69  
    70  		a := int(rand.Int31n(100))
    71  		b := int(rand.Int31n(100))
    72  		p := payload.New(map[string]int{"a": a, "b": b})
    73  
    74  		result := <-bkrServer.Call("math.add", p)
    75  
    76  		if result.Error() != nil {
    77  			fmt.Printf("%s", result.Error())
    78  		} else {
    79  			fmt.Printf("%d * %d = %d\n", a, b, result.Int()) //$ result: 140
    80  		}
    81  
    82  		wg.Done()
    83  	})
    84  
    85  	bkrClient.Start()
    86  
    87  	wg.Wait()
    88  
    89  	bkrClient.Stop()
    90  	bkrServer.Stop()
    91  }