1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| case class LuckyEvent( //抽奖成功事件 userId: Long, luckyMoney: Int ) case class FailureEvent( //抽奖失败事件 userId: Long, reason: String ) case class Lottery( totalAmount: Int, //红包总金额 remainAmount: Int //剩余红包金额 ) { def update(luckyMoney: Int) = { copy( remainAmount = remainAmount - luckyMoney ) } } class LotteryActor(initState: Lottery) extends PersistentActor with ActorLogging{ override def persistenceId: String = "lottery-actor-1"
var state = initState
override def receiveRecover: Receive = { case event: LuckyEvent => updateState(event) case SnapshotOffer(_, snapshot: Lottery) => log.info(s"Recover actor state from snapshot and the snapshot is ${snapshot}") state = snapshot case RecoveryCompleted => log.info("the actor recover completed") }
def updateState(le: LuckyEvent) = state = state.update(le.luckyMoney)
override def receiveCommand: Receive = { case lc: LotteryCmd => doLottery(lc) match { case le: LuckyEvent => persist(le) { event => updateState(event) increaseEvtCountAndSnapshot() sender() ! event } case fe: FailureEvent => sender() ! fe } case "saveSnapshot" => saveSnapshot(state) case SaveSnapshotSuccess(metadata) => ??? }
private def increaseEvtCountAndSnapshot() = { val snapShotInterval = 5 if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0) { self ! "saveSnapshot" } }
def doLottery(lc: LotteryCmd) = { if (state.remainAmount > 0) { val luckyMoney = scala.util.Random.nextInt(state.remainAmount) + 1 LuckyEvent(lc.userId, luckyMoney) } else { FailureEvent(lc.userId, "下次早点来,红包已被抽完咯!") } } }
|