Jor*_*ade 5 java backend dropwizard microservices
在 Dropwizard 应用程序中,Application 类中的抽象 run 方法通常在主服务中重写,如下所示:
@Override
public void run(MyServiceConfiguration configuration, Environment environment) throws Exception {
// application logic
}
Run Code Online (Sandbox Code Playgroud)
我尝试跟踪执行逻辑,但无法弄清楚该方法在哪里/如何被调用。有人能指出我正确的方向吗?
让我们从头开始,当您将Dropwizard 应用程序作为服务器运行时,您将server在命令行界面 (CLI) 上发出命令。文档给出的示例是:
java -jar target/hello-world-0.0.1-SNAPSHOT.jar 服务器 hello-world.yml
在io.dropwizard.Application(您通常扩展的)中,我们可以看到以下命令被添加到bootstrap:
protected void addDefaultCommands(Bootstrap<T> bootstrap) {
bootstrap.addCommand(new ServerCommand<>(this));
bootstrap.addCommand(new CheckCommand<>(this));
}
Run Code Online (Sandbox Code Playgroud)
在本例中this,是扩展类的实例Application,该实例被赋予ServerCommand.
然后run同一个类中的方法将解析 CLI:
public void run(String... arguments) throws Exception {
final Bootstrap<T> bootstrap = new Bootstrap<>(this);
addDefaultCommands(bootstrap);
initialize(bootstrap);
// Should be called after initialize to give an opportunity to set a custom metric registry
bootstrap.registerMetrics();
final Cli cli = new Cli(new JarLocation(getClass()), bootstrap, System.out, System.err);
// only exit if there's an error running the command
cli.run(arguments).ifPresent(this::onFatalError);
}
Run Code Online (Sandbox Code Playgroud)
当我们跟随时, cli.run(arguments).ifPresent(this::onFatalError);我们最终会进入io.dropwizard.cli.Cli#run. 在此方法中,命令被解析,并且由于我们指定,server它将按名称找到该命令并执行它:
public Optional<Throwable> run(String... arguments) {
...
final Namespace namespace = parser.parseArgs(arguments);
final Command command = requireNonNull(commands.get(namespace.getString(COMMAND_NAME_ATTR)),
"Command is not found");
try {
command.run(bootstrap, namespace);
...
Run Code Online (Sandbox Code Playgroud)
服务器命令将是 的一个实例io.dropwizard.cli.ServerCommand,它扩展了io.dropwizard.cli.EnvironmentCommand.
在 中EnvironmentCommand我们可以看到您请求的Application.run(...)方法被执行:
protected void run(Bootstrap<T> bootstrap, Namespace namespace, T configuration) throws Exception {
...
bootstrap.run(configuration, environment);
application.run(configuration, environment);
run(environment, namespace, configuration);
}
Run Code Online (Sandbox Code Playgroud)
这一行具体是:
application.run(配置,环境);
是T configuration通过 的基类添加的EnvironmentCommand,即io.dropwizard.cli.ConfiguredCommand。
所有代码均取自 Dropwizard 版本2.1.0