当前位置:  开发笔记 > 编程语言 > 正文

使用Scala和Spray.io从Future onComplete案例返回一个字符串

如何解决《使用Scala和Spray.io从FutureonComplete案例返回一个字符串》经验,为你挑选了0个好方法。

我正在尝试使用喷射路由和弹性搜索(使用elastic4s)编写一个小的休息api,以提高我的scala级别.这是我的路线定义:

package com.example

import akka.actor.Actor
import spray.routing._
import com.example.core.control.CrudController

class ServiceActor extends Actor with Service {
  def actorRefFactory = context
  def receive = runRoute(routes)
}

trait Service extends HttpService {

  val crudController = new CrudController()
  val routes = {
      path("ads" / IntNumber) { id =>
      get {
          ctx =>
              ctx.complete(
                crudController.getFromElasticSearch
              )
      }
      }
  }
}

这是我的crudController:

class CrudController extends elastic4s
{

    def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => println(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "{value:hey} \n"
    }
}

方法getFromElasticSearch通过我的trait get封装对库elastic4s的调用.

trait elastic4s {
    def get: Future[SearchResponse] = {
    val client = ElasticClient.local
    client execute { search in "ads"->"categories" }
    }

该库通过client.execute方法返回Future [SearchResponse]对象

我希望我的方法getFromElasticSearch能够对searchResponse应用一些修改(如验证,序列化..),可能是这样的:

def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => someOperations(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "{value:hey} \n"
}

def someOperations(response: SearchResponse) : String = {
    println(" Doing some operations " + response)
    "result of operations"
}

但是如何将"someOperations()"的输出字符串发送到我的喷涂路由路由声明的完整方法?(而不是返回"{value:嘿} \n")这是最好的方法吗?

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有