使用 spring-boot
和 jetty
,我希望能够配置我的应用程序以监听额外的端口,这些端口是在运行时以编程方式添加的(+ 已删除?)。
我尝试过的:
我关注了this tutorial ,这让我可以在多个端口上收听。这非常有效,但不幸的是只在启动时有效。
我试过@Autowiring
org.eclipse.jetty.server.Server
类到服务中,以便我可以添加连接器 - 我收到错误 No qualifying bean of type [org.eclipse.jetty.server.Server] found ...
build.gradle(依赖
buildscript {
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}
apply plugin: 'spring-boot'
...
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile "org.springframework.boot:spring-boot-starter-jetty"
compile "org.eclipse.jetty:jetty-proxy:9.2.17.v20160517"
...
不确定从这里尝试什么...
最佳答案
您可以从 Boot 的 JettyEmbeddedServletContainer
获取 Jetty Server
,它可从 EmbeddedWebApplicationContext
获得。一旦您获得了 Server
,您就可以使用 Jetty 的 API 添加新的连接器。
这是一个添加新连接器以响应正在发布的 ApplicationReadyEvent
的示例:
@Bean
public JettyCustomizer jettyCustomizer(EmbeddedWebApplicationContext context) {
return new JettyCustomizer(
(JettyEmbeddedServletContainer) context.getEmbeddedServletContainer());
}
static class JettyCustomizer implements ApplicationListener<ApplicationReadyEvent> {
private final JettyEmbeddedServletContainer container;
JettyCustomizer(JettyEmbeddedServletContainer container) {
this.container = container;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
Server server = this.container.getServer();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8081);
server.addConnector(connector);
try {
connector.start();
}
catch (Exception ex) {
throw new IllegalStateException("Failed to start connector", ex);
}
}
}
您应该在日志中看到默认连接器从端口 8080 开始,然后是第二个连接器从 8081 开始:
2016-08-16 10:28:57.476 INFO 71330 --- [ main] o.e.jetty.server.AbstractConnector : Started ServerConnector@64bc21ac{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2016-08-16 10:28:57.478 INFO 71330 --- [ main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8080 (http/1.1)
2016-08-16 10:28:57.482 INFO 71330 --- [ main] o.e.jetty.server.AbstractConnector : Started ServerConnector@664a9613{HTTP/1.1,[http/1.1]}{0.0.0.0:8081}
2016-08-16 10:28:57.483 INFO 71330 --- [ main] sample.jetty.SampleJettyApplication : Started SampleJettyApplication in 1.838 seconds (JVM running for 2.132)
关于java - SpringBoot > 在运行时以编程方式添加 Jetty 服务器连接器端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38968121/