使用ask模式在akka中的响应

时间:2017-02-14 21:14:51

标签: scala akka

我尝试使用ask模式得到我的演员的回应 在询问回复中我有List(scala.concurrent.impl.CallbackRunnable@33d40b3) 但我希望得到字符串“1,2” 我怎么能得到预期的结果?

这是我的代码:

class Storage extends Actor {
  var map:ListBuffer[List[String]] = new ListBuffer
  val logger = Logging(context.system,this)

  override def receive = {
    case setRequest(url, urlType)=>
      map+=List(  url, urlType)
      logger.info(s"Putting ${url} to storage")
      sender() ! Status.Success

    case getRequest()=>
      if (map.length >=1){
        var response= map(0).mkString(",")
        logger.info(s"Send ${response}")
        map = map.filter(x => x != response)
        sender ! response
      }
      else{
        sender()! Status.Failure(new emptyStorage)
      }
    case getLength()=>
      sender()! map.length
  }
}

object Main extends  App{
  implicit val timeout = Timeout(5 seconds)
  val system = ActorSystem.create("default-dispatcher", ConfigFactory.load().getConfig("MyDispatcherExample"))
  val storage = system.actorOf(Props(new Storage))
  storage ! setRequest("1", "2")
  val result = Future {storage ? getRequest }
  result onComplete{
    case Success(result)=> println(result)
    case Failure(result)=> println("some  error")
  }
}

1 个答案:

答案 0 :(得分:3)

问询模式本身会返回一个Future,您可以将Future包裹在另一个Future[Future[Any]]中,然后给我们val result = storage ? getRequest result onComplete { case Success(res) => println(res) case Failure(e) => println(e) } 。没有必要:

case class Response(result: String)

此外,当您在Akka中传递数据时,尤其是受类型擦除影响的通用数据类型时,建议将它们包装在案例类中。例如:

Future

问题返回的mapTo也是无类型的。建议使用val result: Future[Response] = (storage ? getRequest).mapTo[Response] 来转换为类型化响应:

<?php
include($_SERVER['DOCUMENT_ROOT'].'/includes/dbh.php');
$newNote = mysqli_real_escape_string($conn, $_POST['note']);

if (empty($newNote)){
        header("Location: /admin/notes.php?error=empty");
        exit();
} else {
        $sql = "INSERT INTO notes (note) VALUES ('$NewNote')";
        $result = mysqli_query($conn, $sql);
        header("Location: /admin/notes.php?success");
    }
?>


<div class="section">
  <div class="container">
    <?php
     $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
     if (strpos($url, 'error=empty') !== false) {
       echo "<div class='alert alert-danger'>Error: You must enter some text!</div>";
     }
     elseif (strpos($url, 'success') !== false) {
       echo "<div class='alert alert-success'>Note successfully submitted!</div>";
     }
    ?>
    <h3>Add Note</h3>
    <form action="/admin/includes/notes.inc.php" method="post">
      <div class="form-group">
        <textarea name="note" class="form-control m20" rows="5"></textarea>
        <button type="submit" name="submit" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> Submit</button>
      </div>
    </form>
  </div>
</div>