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

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	console "github.com/AsynkronIT/goconsole"
     8  	"github.com/AsynkronIT/protoactor-go/actor"
     9  )
    10  
    11  type hello struct{ Who string }
    12  type helloActor struct{}
    13  
    14  func (state *helloActor) Receive(context actor.Context) {
    15  	switch msg := context.Message().(type) {
    16  	case *actor.Started:
    17  		fmt.Println("Started, initialize actor here")
    18  	case *actor.Stopping:
    19  		fmt.Println("Stopping, actor is about shut down")
    20  	case *actor.Stopped:
    21  		fmt.Println("Stopped, actor and it's children are stopped")
    22  	case *actor.Restarting:
    23  		fmt.Println("Restarting, actor is about restart")
    24  	case *hello:
    25  		fmt.Printf("Hello %v\n", msg.Who)
    26  	}
    27  }
    28  
    29  func main() {
    30  	rootContext := actor.EmptyRootContext
    31  	props := actor.PropsFromProducer(func() actor.Actor { return &helloActor{} })
    32  	pid := rootContext.Spawn(props)
    33  	rootContext.Send(pid, &hello{Who: "Roger"})
    34  	//rootContext.Send(pid, &hello{Who: "Roger"})
    35  
    36  	// why wait?
    37  	// Stop is a system message and is not processed through the user message mailbox
    38  	// thus, it will be handled _before_ any user message
    39  	// we only do this to show the correct order of events in the console
    40  	time.Sleep(1 * time.Second)
    41  	rootContext.Stop(pid)
    42  	console.ReadLine()
    43  }