github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/23_proto_actor/cluster-broadcast/node1/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/AsynkronIT/goconsole"
     6  	"github.com/AsynkronIT/protoactor-go/actor"
     7  	"github.com/AsynkronIT/protoactor-go/cluster"
     8  	"github.com/AsynkronIT/protoactor-go/cluster/consul"
     9  	"github.com/AsynkronIT/protoactor-go/examples/cluster-broadcast/shared"
    10  	"github.com/AsynkronIT/protoactor-go/remote"
    11  	"log"
    12  	"time"
    13  )
    14  
    15  func main() {
    16  	startNode(8080)
    17  
    18  	fmt.Print("\nBoot other nodes and press Enter\n")
    19  	console.ReadLine()
    20  	calcAdd("Eggs", 1)
    21  	calcAdd("Eggs", 10)
    22  
    23  	calcAdd("Bananas", 1000)
    24  
    25  	calcAdd("Meat", 3)
    26  	calcAdd("Meat", 9000)
    27  
    28  	getAll()
    29  
    30  	console.ReadLine()
    31  
    32  	cluster.Shutdown(true)
    33  }
    34  
    35  func startNode(port int64) {
    36  	// how long before the grain poisons itself
    37  	timeout := 10 * time.Minute
    38  
    39  	// this node knows about Hello kind
    40  	remote.Register("Calculator", actor.PropsFromProducer(func() actor.Actor {
    41  		return &shared.CalculatorActor{
    42  			Timeout: &timeout,
    43  		}
    44  	}))
    45  
    46  	// this node knows about Hello kind
    47  	remote.Register("Tracker", actor.PropsFromProducer(func() actor.Actor {
    48  		return &shared.TrackerActor{
    49  			Timeout: &timeout,
    50  		}
    51  	}))
    52  
    53  	shared.CalculatorFactory(func() shared.Calculator {
    54  		return &shared.CalcGrain{}
    55  	})
    56  
    57  	shared.TrackerFactory(func() shared.Tracker {
    58  		return &shared.TrackGrain{}
    59  	})
    60  
    61  	cp, err := consul.New()
    62  	if err != nil {
    63  		log.Fatal(err)
    64  	}
    65  	cluster.Start("mycluster", fmt.Sprintf("127.0.0.1:%v", port), cp)
    66  }
    67  
    68  func calcAdd(grainId string, addNumber int64) {
    69  	calcGrain := shared.GetCalculatorGrain(grainId)
    70  	total1, err := calcGrain.Add(&shared.NumberRequest{Number: addNumber})
    71  	if err != nil {
    72  		panic(err)
    73  	}
    74  
    75  	fmt.Printf("Grain: %v - Total: %v \n", calcGrain.ID, total1.Number)
    76  }
    77  
    78  func getAll() {
    79  	trackerGrain := shared.GetTrackerGrain("singleTrackerGrain")
    80  	totals, err := trackerGrain.BroadcastGetCounts(&shared.Noop{})
    81  	if err != nil {
    82  		panic(err)
    83  	}
    84  
    85  	fmt.Println("--- Totals ---")
    86  	for grainId, count := range totals.Totals {
    87  		fmt.Printf("%v : %v\n", grainId, count)
    88  	}
    89  }