给出以下代码
import akka.NotUsed;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.server.AllDirectives;
import akka.http.javadsl.server.Route;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Flow;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import java.util.concurrent.CompletionStage;
public class Server extends AllDirectives {
// set up ActorSystem and other dependencies here
static ActorSystem system; // = ActorSystem.create("pci-enclave");
static Http http; // = Http.get(system);
static ActorMaterializer materializer; // = ActorMaterializer.create(system);
public Server(ActorSystem system) {
}
public static void main(String[] args) throws Exception {
// Create an Actor System in order to materialize HTTP Streams, and other purposes.
system = ActorSystem.create("foobar");
http = Http.get(system);
materializer = ActorMaterializer.create(system);
// In order to access all route directives we need an instance where the routes are define.
Server server = new Server(system);
final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = server.routeRoot().flow(system, materializer);
final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow,
ConnectHttp.toHost("localhost", 8080), materializer);
System.out.println("Server online at http://localhost:8080/\nPress RETURN to stop...");
System.in.read(); // let it run until user presses return
binding
.thenCompose(ServerBinding::unbind) // trigger unbinding from the port
.thenAccept(unbound -> system.terminate()); // and shutdown when done
}
protected Route routeRoot() {
return
route(
// We can't use static methods because kka.http.javadsl.server.directives.RouteDirectives.route
// cannot be called in a static context--too bad, so sad. Would have been nicer to just say
// Foo(system).route(), Bar(system).route()
new Foo(system).route(), // http:.../foo/...
new Bar(system).route() // http:.../bar/...
);
}
}
运行良好;如果我尝试在类初始值设定项中初始化Actor系统,则会得到
[error] (run-main-0) java.lang.ExceptionInInitializerError
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
Caused by: com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'akka'
为什么会失败?
在初始化程序中是否有一些特殊的魔术来初始化Akka?
我曾经在Scala中构建Akka系统,但在这种情况下,我需要在Java中构建一些东西。