我有一个简单的scala类CartService,它创建一个actor并向它发送一些消息,并且actor通过它发回一个响应 发件人!结果 演员代码
package actors
import java.util.UUID
import akka.persistence.PersistentActor
import entites._
/**
* Created by spineor on 12/12/16.
*/
//Command to be processed by the Actors
case class AddSkuToCartCmd(cart_id :UUID, sku_id :String, price :Double)
case class RemoveSkufromCmd(cart_id :UUID, sku_id :String)
case class ChangeSkuQuantityCmd(cart_id: UUID, sku_id: String, new_quantity: Int)
case class GetCartUniqueSkuCountCmd(cart_id: UUID)
case class CheckoutCartCmd(cart_id: UUID)
//Events to be persisted in Journal
case class AddedSkutoCartEvent(cart_id :UUID, sku_id:String, price :Double)
case class RemovedSkuFromCartEvent(cart_id :UUID, sku_id :String)
case class ChangeSkuQuantityEvent(cart_id: UUID, sku_id: String, new_quantity: Int)
class CartActor extends PersistentActor{
import kafka.producerConsumer._
var cart :Cart = _
override def preStart() {
val actorName = self.path.name
println("hi2")
var cart_entries = Map[String, CartEntry]()
var cart_new = new Cart(UUID.fromString(actorName), cart_entries)
cart = cart_new
}
override def receiveRecover: Receive = {
case AddedSkutoCartEvent(cart_id , sku_id, price) =>
addSkutoCart(cart_id,sku_id, price)
case RemovedSkuFromCartEvent(cart_id , sku_id) =>
removeSkufromCart(cart_id,sku_id)
case ChangeSkuQuantityEvent(cart_id , sku_id, new_quantity) =>
changeSkuQuantity(cart_id,sku_id, new_quantity)
case CheckoutCartCmd(cart_id) =>
case GetCartUniqueSkuCountCmd(cart_id) =>
println("in recover")
}
override def receiveCommand: Receive = {
case AddSkuToCartCmd(cart_id , sku_id, price) =>
println("hi")
persist(AddedSkutoCartEvent(cart_id , sku_id, price)) (evt =>{
addSkutoCart(cart_id,sku_id, price)
})
case RemoveSkufromCmd(cart_id , sku_id) =>
persist(RemovedSkuFromCartEvent(cart_id , sku_id)) (evt =>{
removeSkufromCart(cart_id,sku_id)
})
case ChangeSkuQuantityCmd(cart_id, sku_id, new_quantity) =>
persist(ChangeSkuQuantityEvent(cart_id, sku_id, new_quantity)) (evt =>{
changeSkuQuantity(cart_id, sku_id, new_quantity)
})
case GetCartUniqueSkuCountCmd(cart_id) =>
sender ! getCartUniqueSkuCount(cart_id)
case CheckoutCartCmd(cart_id) =>
checkoutCart(cart_id)
}
override def persistenceId: String = self.path.name
def addSkutoCart(cart_id: UUID, sku_id: String, price: Double) : UUID= {
var entries = cart.cart_entries
val new_entry = CartEntry(sku_id, 1, price)
val new_entries = entries + (sku_id -> new_entry)
cart.cart_entries = new_entries
cart.cart_id
}
def changeSkuQuantity(cart_id: UUID ,sku_id: String ,new_quant: Int)= {
var entries = cart.cart_entries
if(entries.contains(sku_id)){
//If sku is already present increase quantity by 1 set price as latest received and update the entries map
var cart_entry = entries.get(sku_id).get
var new_quantity = new_quant
var new_price = cart_entry.price
val new_entry = CartEntry(sku_id, new_quantity, new_price)
entries + (sku_id -> new_entry)
}
else{
//TODO : Throw Exception , item to be updated is not present in cart
}
/*for ((k,v) <- entries) printf("key: %s, value: %s\n", k, v)*/
}
def removeSkufromCart(cart_id: UUID, sku_id: String) = {
var entries = cart.cart_entries
var new_entries = entries - sku_id
cart.cart_entries = new_entries
}
def getCartUniqueSkuCount(cart_id: UUID): Int = {
val count = cart.cart_entries.size
count
}
def checkoutCart(cart_id: UUID) = {
val cartProducer = Producer[Cart]("Cart-Update-Topic")
cartProducer.send(cart)
//Consumer Test Code
/*val consumer = SingleTopicConsumer("Cart-Update-Topic")
var entries = cart.cart_entries
var cart3 = new Cart(cart.cart_id,entries)
cartProducer.send(cart3)
entries += "ABC" -> new CartEntry("ABC",12,213)
val kafkaCart = consumer.read()*/
}
}
和服务代码
package services
import java.util.UUID
import actors._
import akka.actor.{ActorRef, ActorSystem, Props}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.util.{Failure, Success}
import scala.concurrent.duration.Duration
/**
* Created by spineor on 9/12/16.
*/
class CartService {
var system = ActorSystem("System")
def addSkutoCart(cart_id :UUID, sku_id :String, price :Double) :String = {
//get Actor for this cart_id
//implicit val timeout: Timeout = 20 seconds
val cart_actor = routeMessagesToCart(cart_id)
cart_actor ! AddSkuToCartCmd(cart_id, sku_id ,price)
cart_actor.path.name
}
def removeSkuFromCart(cart_id :UUID, sku_id :String) = {
//get Actor for this cart_id
val cart_actor = routeMessagesToCart(cart_id)
cart_actor ! RemoveSkufromCmd(cart_id, sku_id )
}
def changeSkuQuantity(cart_id: UUID,sku_id: String ,new_quantity: Int) = {
val cart_actor = routeMessagesToCart(cart_id)
cart_actor ! ChangeSkuQuantityCmd(cart_id, sku_id, new_quantity)
}
def checkoutCart(cart_id: UUID) ={
val cart_actor = routeMessagesToCart(cart_id)
cart_actor ! CheckoutCartCmd(cart_id)
}
/*This is cental method to locate cart Actors in the node
in case a actor is not present or has terminated ,it will be created
In case of a terminated cart actor ,its previous events will be replayed
from the journal first and then the new message is applied
The Cart actor name and its persistence id both are same as the Cart's unique UUID*/
def routeMessagesToCart(cart_id: UUID): ActorRef = {
var cartActor :ActorRef = null
if(null == cart_id){
//No cart id in request create a new Cart Actor for the request
val new_cart_id = createNewCartId()
cartActor = system.actorOf(Props[CartActor],new_cart_id.toString)
cartActor
}
//Find if actor for the cart already exists,or is Terminated
else{
implicit val timeout = Timeout(5 seconds)
val name = "/user/" + cart_id.toString
val future = system.actorSelection("/user/" + cart_id.toString).resolveOne()
future onComplete {
case Success(v) => { cartActor = v
}
case Failure(e) => {
//The cart actor no longer exists and must be recreated
cartActor = system.actorOf(Props[CartActor],cart_id.toString)
}
}
//Sleep for Actor to be created
Thread.sleep(500)
cartActor
}
}
/*
This method creates a new random UUID which is used to uniquely
identify the cart and thus cart actors
*/
def createNewCartId() :UUID = {
val cart_id = UUID.randomUUID()
cart_id
}
def getCartUniqueSkuCount(cart_id: UUID) ={
val cart_actor = routeMessagesToCart(cart_id)
implicit val timeout = Timeout(15 seconds)
val count = cart_actor ? GetCartUniqueSkuCountCmd(cart_id)
val result = Await.result(count, 15 second)
result
/*count onComplete {
case Success(x) => println("Unique Items in cart : " + x)
case Failure(t) => println("An error has occured: " + t.getMessage)
}*/
}
}
现在我正在为该服务编写一个测试用例 我在哪里创建一个服务对象,并调用将消息发送给actor的服务方法
val service = new CartService()
val new_cart_id = UUID.fromString(service.addSkutoCart(null, "12", 12))
val count = service.getCartUniqueSkuCount(new_cart_id)
但这次等待时间过去了,我收到了一条消息
[INFO] [12/28/2016 16:07:10.441] [System-akka.actor.default-dispatcher-7] [akka:// System / user / fd38f1b1-6f03-4997-8625-0ce7e0ef2626]从Actor [akka:// System / temp / $ a]到Actor [akka:// System / user / fd38f1b1-6f03-4997-8625-0ce7e0ef2626#279696660]的消息[actors.GetCartUniqueSkuCountCmd]未送达。 [2]遇到死信。可以使用配置设置关闭或调整此日志记录&#39; akka.log-dead-letters&#39;和&#39; akka.log-dead-letters-during-shutdown&#39;。
从一些谷歌搜索我知道它与发送者被关闭有关,但我无法解决这个问题。 任何意见都表示赞赏。
这是stacktrace:
java.util.concurrent.TimeoutException:期货在[15]之后超时 秒] scala.concurrent.impl.Promise $ DefaultPromise.ready(Promise.scala:219) 在 scala.concurrent.impl.Promise $ DefaultPromise.result(Promise.scala:223) 在scala.concurrent.Await $$ anonfun $ result $ 1.apply(package.scala:190) 在
scala.concurrent.BlockContext $ $ DefaultBlockContext .blockOn(BlockContext.scala:53) 在scala.concurrent.Await $ .result(package.scala:190)at services.CartService.getCartUniqueSkuCount(CartService.scala:103)at CartActorSpec $$ anonfun $ 1 $$ anonfun $ $应用MCV $ SP $ 1.适用$ MCV $ SP(CartActorSpec.scala:48) 在 CartActorSpec $$ anonfun $ 1 $$ anonfun $ $应用MCV $ SP $ 1.适用(CartActorSpec.scala:44) 在 CartActorSpec $$ anonfun $ 1 $$ anonfun $ $应用MCV $ SP $ 1.适用(CartActorSpec.scala:44) 在 org.scalatest.Transformer $$ anonfun $ $应用$ 1.适用MCV $ SP(Transformer.scala:22) 在org.scalatest.OutcomeOf $ class.outcomeOf(OutcomeOf.scala:85)at at org.scalatest.OutcomeOf $ .outcomeOf(OutcomeOf.scala:104)at at org.scalatest.Transformer.apply(Transformer.scala:22)at org.scalatest.Transformer.apply(Transformer.scala:20)at org.scalatest.WordSpecLike $$ anon $ 1.apply(WordSpecLike.scala:953)at at org.scalatest.Suite $ class.withFixture(Suite.scala:1122)at CartActorSpec.withFixture(CartActorSpec.scala:19)at org.scalatest.WordSpecLike $ class.invokeWithFixture $ 1(WordSpecLike.scala:950) 在 org.scalatest.WordSpecLike $$ anonfun $ $的runTest 1.适用(WordSpecLike.scala:962) 在 org.scalatest.WordSpecLike $$ anonfun $ $的runTest 1.适用(WordSpecLike.scala:962) 在org.scalatest.SuperEngine.runTestImpl(Engine.scala:306)at org.scalatest.WordSpecLike $ class.runTest(WordSpecLike.scala:962)at at CartActorSpec.runTest(CartActorSpec.scala:19)at org.scalatest.WordSpecLike $$ anonfun $ runTests $ 1.适用(WordSpecLike.scala:1021) 在 org.scalatest.WordSpecLike $$ anonfun $ runTests $ 1.适用(WordSpecLike.scala:1021) 在 org.scalatest.SuperEngine $$ anonfun $ traverseSubNodes $ 1 $ 1.适用(Engine.scala:413) 在 org.scalatest.SuperEngine $$ anonfun $ traverseSubNodes $ 1 $ 1.适用(Engine.scala:401) 在scala.collection.immutable.List.foreach(List.scala:381)at org.scalatest.SuperEngine.traverseSubNodes $ 1(Engine.scala:401)at at org.scalatest.SuperEngine.org $ scalatest $ SuperEngine $$ runTestsInBranch(Engine.scala:390) 在 org.scalatest.SuperEngine $$ anonfun $ traverseSubNodes $ 1 $ 1.适用(Engine.scala:427) 在 org.scalatest.SuperEngine $$ anonfun $ traverseSubNodes $ 1 $ 1.适用(Engine.scala:401) 在scala.collection.immutable.List.foreach(List.scala:381)at org.scalatest.SuperEngine.traverseSubNodes $ 1(Engine.scala:401)at at org.scalatest.SuperEngine.org $ scalatest $ SuperEngine $$ runTestsInBranch(Engine.scala:396) 在org.scalatest.SuperEngine.runTestsImpl(Engine.scala:483)at at org.scalatest.WordSpecLike $ class.runTests(WordSpecLike.scala:1021)at at CartActorSpec.runTests(CartActorSpec.scala:19)at org.scalatest.Suite $ class.run(Suite.scala:1424)at CartActorSpec.org $ scalatest $ WordSpecLike $$超$运行(CartActorSpec.scala:19) 在 org.scalatest.WordSpecLike $$ anonfun $运行$ 1.适用(WordSpecLike.scala:1067) 在 org.scalatest.WordSpecLike $$ anonfun $运行$ 1.适用(WordSpecLike.scala:1067) 在org.scalatest.SuperEngine.runImpl(Engine.scala:545)at org.scalatest.WordSpecLike $ class.run(WordSpecLike.scala:1067)at at CartActorSpec.org $ scalatest $ BeforeAndAfterAll $$超$运行(CartActorSpec.scala:19) 在 org.scalatest.BeforeAndAfterAll $ class.liftedTree1 $ 1(BeforeAndAfterAll.scala:257) 在 org.scalatest.BeforeAndAfterAll $ class.run(BeforeAndAfterAll.scala:256) 在CartActorSpec.run(CartActorSpec.scala:19)
PS我的测试类中确实有ImplictSender特性
class CartActorSpec extends TestKit(ActorSystem("CartActorSpec"))
with WordSpecLike
with Matchers
with BeforeAndAfterAll
with ImplicitSender {...}