Handle Akka HttpRequest with actors?

时间:2017-06-15 10:37:05

标签: akka akka-http akka-stream akka-actor

ActorRef actor = ...;

Flow<HttpRequest, HttpResponse, NotUsed> flow = Flow
    .of(HttpRequest.class)
    .via(Flow.fromSinkAndSource(
        Sink
            .actorRef(actor, "COMPLETED"),
        Source
            .actorRef(4, OverflowStrategy.fail())
            .mapMaterializedValue(sourceActor -> {
                actor.tell("REGISTER", sourceActor);
                return sourceActor;
            })
        ))
    .map(info -> (HttpResponse) info);

connection.handleWith(flow, materializer);

I create an actor when a connection accepted, and handle the HttpRequest with this actor.

Question(1): Is there a better way to implement this?

Question(2): Now, requests from a connection is sent to the same actor, and I can retrieve a token from a HttpRequest. How can I send requests to a specific actor base on the token? The pseudocode as follow is what I try to do.

Flow<HttpRequest, HttpResponse, NotUsed> flow = Flow
    .of(HttpRequest.class)
    .via(
        .........................................................
        String token = retrieveTokenFromHttpRequest(HttpRequest);
        ActorRef actor = actorContainer.get(token);
        .........................................................
        Flow.fromSinkAndSource(
            Sink
                .actorRef(actor, "COMPLETED"),
            Source
                .actorRef(4, OverflowStrategy.fail())
                .mapMaterializedValue(sourceActor -> {
                    actor.tell("REGISTER", sourceActor);
                    return sourceActor;
                })
            )
    )
    .map(info -> (HttpResponse) info);

connection.handleWith(flow, materializer);

0 个答案:

没有答案