use of io.vertx.core.http.HttpServer in project vert.x by eclipse.
the class HttpServerImpl method listen.
public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
if (requestStream.handler() == null && wsStream.handler() == null) {
throw new IllegalStateException("Set request or websocket handler first");
}
if (listening) {
throw new IllegalStateException("Already listening");
}
listenContext = vertx.getOrCreateContext();
listening = true;
serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
List<HttpVersion> applicationProtocols = options.getAlpnVersions();
if (listenContext.isWorkerContext()) {
applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2).collect(Collectors.toList());
}
sslHelper.setApplicationProtocols(applicationProtocols);
synchronized (vertx.sharedHttpServers()) {
// Will be updated on bind for a wildcard port
this.actualPort = port;
id = new ServerID(port, host);
HttpServerImpl shared = vertx.sharedHttpServers().get(id);
if (shared == null || port == 0) {
serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
bootstrap.channel(NioServerSocketChannel.class);
applyConnectionOptions(bootstrap);
sslHelper.validate(vertx);
bootstrap.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
if (requestStream.isPaused() || wsStream.isPaused()) {
ch.close();
return;
}
ChannelPipeline pipeline = ch.pipeline();
if (sslHelper.isSSL()) {
pipeline.addLast("ssl", sslHelper.createSslHandler(vertx));
if (options.isUseAlpn()) {
pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") {
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
if (protocol.equals("http/1.1")) {
configureHttp1(pipeline);
} else {
handleHttp2(ch);
}
}
});
} else {
configureHttp1(pipeline);
}
} else {
if (DISABLE_HC2) {
configureHttp1(pipeline);
} else {
pipeline.addLast(new Http1xOrHttp2Handler());
}
}
}
});
addHandlers(this, listenContext);
try {
bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
bindFuture.addListener(res -> {
if (res.failed()) {
vertx.sharedHttpServers().remove(id);
} else {
Channel serverChannel = res.result();
HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
serverChannelGroup.add(serverChannel);
metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
}
});
} catch (final Throwable t) {
// Make sure we send the exception back through the handler (if any)
if (listenHandler != null) {
vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
} else {
// No handler - log so user can see failure
log.error(t);
}
listening = false;
return this;
}
vertx.sharedHttpServers().put(id, this);
actualServer = this;
} else {
// Server already exists with that host/port - we will use that
actualServer = shared;
this.actualPort = shared.actualPort;
addHandlers(actualServer, listenContext);
metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
}
actualServer.bindFuture.addListener(future -> {
if (listenHandler != null) {
final AsyncResult<HttpServer> res;
if (future.succeeded()) {
res = Future.succeededFuture(HttpServerImpl.this);
} else {
res = Future.failedFuture(future.cause());
listening = false;
}
listenContext.runOnContext((v) -> listenHandler.handle(res));
} else if (future.failed()) {
listening = false;
log.error(future.cause());
}
});
}
return this;
}
use of io.vertx.core.http.HttpServer in project java-chassis by ServiceComb.
the class RestServerVerticle method start.
@Override
public void start(Future<Void> startFuture) throws Exception {
super.start();
// 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
if (endpointObject == null) {
LOGGER.warn("rest listen address is not configured, will not start.");
startFuture.complete();
return;
}
Router mainRouter = Router.router(vertx);
mainRouter.route().handler(bodyHandler);
VertxRestServer vertxRestServer = new VertxRestServer(mainRouter);
vertxRestServer.setTransport(CseContext.getInstance().getTransportManager().findTransport(Const.RESTFUL));
HttpServer httpServer = createHttpServer();
httpServer.requestHandler(mainRouter::accept);
startListen(httpServer, startFuture);
}
use of io.vertx.core.http.HttpServer in project vertx-swagger by bobxwang.
the class SwaggerApp method Run.
public static AnnotationConfigApplicationContext Run(Class<?> clasz) {
final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(clasz);
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(ApplicationContextHolder.class);
applicationContext.registerBeanDefinition("applicationContextHolder", bdb.getBeanDefinition());
// Just For Init
applicationContext.getBean(ApplicationContextHolder.class);
final Environment environment = applicationContext.getBean(Environment.class);
final Vertx vertx = applicationContext.getBean(Vertx.class);
final SpringVerticleFactory verticleFactory = new SpringVerticleFactory();
vertx.registerVerticleFactory(verticleFactory);
try {
applicationContext.getBean(Router.class);
} catch (BeansException be) {
if (be instanceof NoSuchBeanDefinitionException) {
Router rr = new RouterImpl(vertx);
applicationContext.getBeanFactory().registerSingleton("router", rr);
}
}
final Router router = applicationContext.getBean(Router.class);
initSwagger(environment);
configRouter(vertx, router, environment);
Map<String, Verticle> maps = applicationContext.getBeansOfType(Verticle.class);
DeploymentOptions options = new DeploymentOptions().setInstances(1).setWorker(true);
for (Map.Entry<String, Verticle> temp : maps.entrySet()) {
Verticle verticle = temp.getValue();
String name = verticle.getClass().getSimpleName().substring(0, 1).toLowerCase() + verticle.getClass().getSimpleName().substring(1);
vertx.deployVerticle(verticleFactory.prefix() + ":" + name, options);
for (Method method : verticle.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(Override.class)) {
continue;
}
if (method.getName().contains("lambda")) {
continue;
}
if (io.swagger.util.ReflectionUtils.isOverriddenMethod(method, verticle.getClass())) {
continue;
}
if (method.isAnnotationPresent(BBRouter.class)) {
BBRouter bbRouter = io.swagger.util.ReflectionUtils.getAnnotation(method, BBRouter.class);
Route route = router.route(bbRouter.httpMethod(), bbRouter.path());
route.handler(ctx -> {
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, verticle, ctx);
});
}
}
}
HttpServer httpServer = vertx.createHttpServer(new HttpServerOptions().setSsl(false).setKeyStoreOptions(new JksOptions().setPath("server-keystore.jks").setPassword("secret")));
httpServer.requestHandler(router::accept);
int port;
try {
port = Integer.valueOf(environment.getProperty("server.port", "8080"));
} catch (Exception e) {
throw new RuntimeException("请配置有效端口号");
}
httpServer.listen(port, ar -> {
if (ar.succeeded()) {
logger.info("Server started on port " + ar.result().actualPort());
} else {
logger.error("Cannot start the server: " + ar.cause());
}
});
return applicationContext;
}
use of io.vertx.core.http.HttpServer in project vertx-examples by vert-x3.
the class VertxHttpServer method start.
@Validate
public void start() throws Exception {
LOGGER.info("Creating vertx HTTP server");
HttpServer server = executeWithTCCLSwitch(() -> vertx.createHttpServer());
server.requestHandler((r) -> {
r.response().end("Hello from OSGi !");
}).listen(8080);
}
use of io.vertx.core.http.HttpServer in project vertx-examples by vert-x3.
the class DashboardVerticle method start.
@Override
public void start() throws Exception {
Router router = Router.router(vertx);
// The event bus bridge handler
BridgeOptions options = new BridgeOptions();
options.setOutboundPermitted(Collections.singletonList(new PermittedOptions().setAddress("dashboard")));
router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options));
// The web server handler
router.route().handler(StaticHandler.create().setCachingEnabled(false));
// Start http server
HttpServer httpServer = vertx.createHttpServer();
httpServer.requestHandler(router::accept).listen(8080, ar -> {
if (ar.succeeded()) {
System.out.println("Http server started");
} else {
ar.cause().printStackTrace();
}
});
// Our dashboard that aggregates metrics from various kafka topics
JsonObject dashboard = new JsonObject();
// Publish the dashboard to the browser over the bus
vertx.setPeriodic(1000, timerID -> {
vertx.eventBus().publish("dashboard", dashboard);
});
// Get the Kafka consumer config
JsonObject config = config();
// Create the consumer
KafkaReadStream<String, JsonObject> consumer = KafkaReadStream.create(vertx, config.getMap(), String.class, JsonObject.class);
// Aggregates metrics in the dashboard
consumer.handler(record -> {
JsonObject obj = record.value();
dashboard.mergeIn(obj);
});
// Subscribe to Kafka
consumer.subscribe(Collections.singleton("the_topic"));
}
Aggregations