1
votes

I am learning Spray and Akka. Have built a simple Spray routing App with one of the route stubs as -

path("blog" / LongNumber) {
  blogId =>
    respondWithMediaType(MediaTypes.`application/json`) {
      get {
        request => BlogFetchActor ! Get(blogId)
      }
    }
 }

In the above code I dispatch a message in my spray route definition (in a class implementing HttpService) to another Actor with an ID (blogId) in the request. The BlogFetchActor is supposed to fetch the data from database and respond to the sender. This I have coded as below -

def receive: Receive = LoggingReceive {
  case Get(id: Long) => {
    log.debug("Retrieving blog with id %d".format(id))
      sender ! ReturnBlog(get(id))
  }
 }

The Actor message from the route is getting to my BlogFetchActor. My BlogFetchActor completes the job of getting the data from the database too. But when I try to send the response back to the sender HttpService, the ReturnBlog message, it does not work. The message ends up in DeadLetters and I see the below in my logs -

Message [in.bharathwrites.BlogFetchActor$ReturnBlog] from Actor[akka://on-spray-can/user/blog-service/blog#1301907662] to Actor[akka://on-spray-can/deadLetters] was not delivered.

Why does the response back to the sender not work? What am I doing wrong? How else can I achieve this? I tried reading the Spray docs and ScalaDoc but could not figure out the problem. Am not proficient enough to read the Spray code and fathom the reasons... Thanks in advance

1

1 Answers

7
votes

If you want to ask another actor before completing a request, you should use Akka's ask pattern (? in the example below).

You may also consider returning an Option[ReturnBlog] instead of ReturnBlog to allow Spray to generate 404 status response automatically if such a blog does not exists.

path("blog" / LongNumber) {
  blogId =>
    respondWithMediaType(MediaTypes.`application/json`) {
      get {
        complete { (BlogFetchActor ? Get(blogId)).mapTo[ReturnBlog] }
      }
    }
}