github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/23_proto_actor/supervision/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 console "github.com/AsynkronIT/goconsole" 7 "github.com/AsynkronIT/protoactor-go/actor" 8 ) 9 10 type hello struct{ Who string } 11 type parentActor struct{} 12 13 func (state *parentActor) Receive(context actor.Context) { 14 switch msg := context.Message().(type) { 15 case *hello: 16 props := actor.PropsFromProducer(newChildActor) 17 child := context.Spawn(props) 18 context.Send(child, msg) 19 } 20 } 21 22 func newParentActor() actor.Actor { 23 return &parentActor{} 24 } 25 26 type childActor struct{} 27 28 func (state *childActor) Receive(context actor.Context) { 29 switch msg := context.Message().(type) { 30 case *actor.Started: 31 fmt.Println("Starting, initialize actor here") 32 case *actor.Stopping: 33 fmt.Println("Stopping, actor is about to shut down") 34 case *actor.Stopped: 35 fmt.Println("Stopped, actor and its children are stopped") 36 case *actor.Restarting: 37 fmt.Println("Restarting, actor is about to restart") 38 case *hello: 39 fmt.Printf("Hello %v\n", msg.Who) 40 panic("Ouch") 41 } 42 } 43 44 func newChildActor() actor.Actor { 45 return &childActor{} 46 } 47 48 func main() { 49 decider := func(reason interface{}) actor.Directive { 50 fmt.Println("handling failure for child") 51 return actor.StopDirective 52 } 53 supervisor := actor.NewOneForOneStrategy(10, 1000, decider) 54 rootContext := actor.EmptyRootContext 55 props := actor. 56 PropsFromProducer(newParentActor). 57 WithSupervisor(supervisor) 58 59 pid := rootContext.Spawn(props) 60 rootContext.Send(pid, &hello{Who: "Roger"}) 61 62 console.ReadLine() 63 }