Last active
February 14, 2019 06:02
-
-
Save oklahomer/cc063682252369296c9684075b7b1682 to your computer and use it in GitHub Desktop.
An example code for https://blog.oklahome.net/2018/09/protoactor-go-messaging-protocol.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/AsynkronIT/protoactor-go/actor" | |
"log" | |
"time" | |
) | |
type pong struct { | |
} | |
type ping struct { | |
} | |
type pingActor struct { | |
pongPid *actor.PID | |
} | |
func (p *pingActor) Receive(ctx actor.Context) { | |
switch ctx.Message().(type) { | |
case struct{}: | |
// Below both work. | |
// | |
//future := p.pongPid.RequestFuture(&ping{}, time.Second) | |
future := ctx.RequestFuture(p.pongPid, &ping{}, time.Second) | |
result, err := future.Result() | |
if err != nil { | |
log.Print(err.Error()) | |
return | |
} | |
log.Printf("Received %#v", result) | |
case *pong: | |
// Never comes here. | |
// When the pong actor responds to the sender, | |
// the sender is not a ping actor but a future process. | |
log.Print("Received pong message") | |
} | |
} | |
func main() { | |
pongProps := actor.FromFunc(func(ctx actor.Context) { | |
switch ctx.Message().(type) { | |
case *ping: | |
log.Print("Received ping message") | |
// Below both work in this example, but their behavior slightly differ. | |
// ctx.Sender().Tell() panics and recovers if the sender is nil; | |
// while ctx.Respond() checks the presence of sender and redirects the message to dead letter process | |
// when sender is absent. | |
// | |
//ctx.Sender().Tell(&pong{}) | |
ctx.Respond(&pong{}) | |
// Take a look at the id field. | |
// 2018/09/23 10:58:53 &actor.PID{Address:"nonhost", Id:"future$3", p:(*actor.Process)(0xc4200ea010)} | |
log.Printf("%#v", ctx.Sender()) | |
// Below all fail because the sender PID does not represents the sender actor, | |
// but the sending Future process and the Future process ends when the first payload is returned. | |
ctx.Sender().Tell(&pong{}) | |
ctx.Respond(&pong{}) | |
ctx.Sender().Tell(&pong{}) | |
ctx.Respond(&pong{}) | |
ctx.Sender().Tell(&pong{}) | |
ctx.Respond(&pong{}) | |
ctx.Sender().Tell(&pong{}) | |
ctx.Respond(&pong{}) | |
default: | |
} | |
}) | |
pongPid := actor.Spawn(pongProps) | |
pingProps := actor.FromProducer(func() actor.Actor { | |
return &pingActor{ | |
pongPid: pongPid, | |
} | |
}) | |
pingPid := actor.Spawn(pingProps) | |
pingPid.Tell(struct{}{}) | |
time.Sleep(1 * time.Second) // Just to make sure system ends after actor execution | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment