import UserStorage._ import akka.actor.{Props, ActorSystem, Stash, Actor} import scala.sys.Prop /** * Created by zzg on 16-4-22. */ case class User2(userName:String,email:String) object UserStorage{ trait DBOperation object DBOperation{ case object Create extends DBOperation case object Update extends DBOperation case object Read extends DBOperation case object Delete extends DBOperation } case object Connect case object Disconnect case class Operation (dBOperation: DBOperation,user2:Option[User2]) } class UserStorage extends Actor with Stash { def receive = disconnected def connected :Actor.Receive = { case Disconnect => println("User Storage Disconnect from DB") //从新设置 context.unbecome() case Operation(op,user) => println(s"User Storage receive ${op} to do in user:${user}") } def disconnected : Actor.Receive = { case Connect => println(s"User Storage connect to DB") unstashAll() //动态切换receive context.become(connected) case _ => stash() } } object BecomeHotswap extends App{ import UserStorage._ val system = ActorSystem("beconHostwap") val userStorage = system.actorOf(Props[UserStorage],"userStorage") userStorage ! Operation(DBOperation.Create,Some(User2("Admin", "admin@packt.com"))) userStorage ! Connect userStorage ! Disconnect Thread.sleep(100) system.shutdown() }
将事件抽象为对象:DBOperation,经过case基于事件判断不一样的事务规则scala
用context.become,unbecome动态热插拔actor颇有用处
code