當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServer類代碼示例

本文整理匯總了Java中io.vertx.core.http.HttpServer的典型用法代碼示例。如果您正苦於以下問題:Java HttpServer類的具體用法?Java HttpServer怎麽用?Java HttpServer使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpServer類屬於io.vertx.core.http包,在下文中一共展示了HttpServer類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: start

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
@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);
  mountAccessLogHandler(mainRouter);
  initDispatcher(mainRouter);

  HttpServer httpServer = createHttpServer();
  httpServer.requestHandler(mainRouter::accept);

  startListen(httpServer, startFuture);
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:21,代碼來源:RestServerVerticle.java

示例2: startListen

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
private void startListen(HttpServer server, Future<Void> startFuture) {
  server.listen(endpointObject.getPort(), endpointObject.getHostOrIp(), ar -> {
    if (ar.succeeded()) {
      LOGGER.info("rest listen success. address={}:{}",
          endpointObject.getHostOrIp(),
          ar.result().actualPort());
      startFuture.complete();
      return;
    }

    String msg = String.format("rest listen failed, address=%s:%d",
        endpointObject.getHostOrIp(),
        endpointObject.getPort());
    LOGGER.error(msg, ar.cause());
    startFuture.fail(ar.cause());
  });
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:18,代碼來源:RestServerVerticle.java

示例3: testSyncAndWaitFiveSecondsForTimeOut

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
@Test
public void testSyncAndWaitFiveSecondsForTimeOut() throws Exception {
  // Create a server that will take a long time to reply to a request.
  final HttpServer timeOutHttpServer = vertx.createHttpServer();
  timeOutHttpServer.requestHandler(
      e -> {
        try {
          Thread.sleep(100000);
        } catch (InterruptedException ex) {
          ex.printStackTrace();
        }
      });
  timeOutHttpServer.listen(TIMEOUT_SERVER_PORT);

  // Send a request synchronously and wait 5 seconds for a response.
  doSync(e -> vertx.createHttpClient().getNow(TIMEOUT_SERVER_PORT, HOST, URI, e::complete), 5);
}
 
開發者ID:StephenFox1995,項目名稱:vertx-sync,代碼行數:18,代碼來源:SyncTest.java

示例4: start

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
@Override
public void start(final Future<Void> startFuture) throws Exception {

    HttpServer http = vertx.createHttpServer();

    Router router = Router.router(vertx);
    router.get("/hello").handler(ctx -> ctx.response().end("World " + System.currentTimeMillis()));

    http.requestHandler(router::accept).listen(11011, result -> {
        if(result.succeeded()){
            System.out.println("Listening on port 11011");
        } else {
            throw new RuntimeException("Server start failed");
        }
    });

}
 
開發者ID:gmuecke,項目名稱:grafana-vertx-datasource,代碼行數:18,代碼來源:BackupVerticle.java

示例5: MetricsFacade

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
public MetricsFacade(Vertx vertx, HttpServer httpServer, int publicationPeriodInMillis) {
  this.httpServer = httpServer;
  this.metricsService = MetricsService.create(vertx);

  logger.info("Scheduling metrics publication every {}ms", publicationPeriodInMillis);

  // ensure that the metrics publication does *not* happen on an event loop thread
  vertx.setPeriodic(
      publicationPeriodInMillis,
      event ->
          vertx.executeBlocking(
              event1 -> {
                JsonObject metrics = metricsService.getMetricsSnapshot(httpServer);
                if (metrics != null) {
                  metricsLogger.info(metrics.encode());
                }
                event1.complete();
              },
              (Handler<AsyncResult<Void>>)
                  event12 -> {
                    // no-op
                  }));
}
 
開發者ID:glytching,項目名稱:dragoman,代碼行數:24,代碼來源:MetricsFacade.java

示例6: startHttpServer

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
private Future<Void> startHttpServer() {
  Future<Void> future = Future.future();
  HttpServer server = vertx.createHttpServer();   // <1>

  Router router = Router.router(vertx);   // <2>
  router.get("/").handler(this::indexHandler);
  router.get("/wiki/:page").handler(this::pageRenderingHandler); // <3>
  router.post().handler(BodyHandler.create());  // <4>
  router.post("/save").handler(this::pageUpdateHandler);
  router.post("/create").handler(this::pageCreateHandler);
  router.post("/delete").handler(this::pageDeletionHandler);

  server
    .requestHandler(router::accept)   // <5>
    .listen(8080, ar -> {   // <6>
      if (ar.succeeded()) {
        LOGGER.info("HTTP server running on port 8080");
        future.complete();
      } else {
        LOGGER.error("Could not start a HTTP server", ar.cause());
        future.fail(ar.cause());
      }
    });

  return future;
}
 
開發者ID:vert-x3,項目名稱:vertx-guide-for-java-devs,代碼行數:27,代碼來源:MainVerticle.java

示例7: start

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
@Override
public void start() throws Exception {

    final Router router = Router.router(vertx);

    final HttpServerOptions httpServerOptions = new HttpServerOptions();
    httpServerOptions.setPort(8900);

    final HttpServer http = vertx.createHttpServer(httpServerOptions);

    SwaggerHandler.registerToRouter(router, MyApp.class);
    final JaxRsRouter jaxRsRouter = new JaxRsRouter();
    final SpringJaxRsHandler handler = new SpringJaxRsHandler(MyApp.class);
    jaxRsRouter.register(MyApp.class, router, handler, handler);
    ManifestHandler.registerToRouter(router);

    http.requestHandler(req -> router.accept(req)).listen(res -> {
        if (res.failed()) {
            res.cause().printStackTrace();
            vertx.close();
        }
    });
}
 
開發者ID:trajano,項目名稱:app-ms,代碼行數:24,代碼來源:EngineSampleMain.java

示例8: main

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
public static void main(String[] args) {
    long time = System.currentTimeMillis();
    Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    Vertx vertx = Vertx.vertx();

    Router router = Router.router(vertx);

    HelloResource helloResource = new HelloResource();
    router.get("/vertx/hello").produces("application/json").handler(helloResource::hello);
    router.route("/vertx/hello").method(HttpMethod.POST).handler(BodyHandler.create());
    router.post("/vertx/hello")
            .consumes("application/json")
            .handler(helloResource::createMessage);

    HttpServerOptions serverOptions = new HttpServerOptions()
            .setPort(8085);
    HttpServer server = vertx.createHttpServer(serverOptions);
    server.requestHandler(router::accept).listen();
    System.out.println("started in " + (System.currentTimeMillis() - time) + " ms");
}
 
開發者ID:cdelmas,項目名稱:microservices-perf,代碼行數:22,代碼來源:Main.java

示例9: configureTheHTTPServer

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
private Future<HttpServer> configureTheHTTPServer() {
    Future<HttpServer> future = Future.future();

    // Use a Vert.x Web router for this REST API.
    Router router = Router.router(vertx);
    router.get(config.getString("http.root")).handler(context -> {
        Future<List<JsonObject>> jdbcFuture = retrieveOperations();
        jdbcFuture.setHandler(jdbc -> {
            if (jdbc.succeeded()) {
                context.response()
                        .putHeader("Content-Type", "application/json")
                        .setStatusCode(200)
                        .end(Json.encodePrettily(jdbcFuture.result()));
            } else {
                context.response().setStatusCode(500).end(jdbc.cause().toString());
            }
        });
    });

    vertx.createHttpServer()
            .requestHandler(router::accept)
            .listen(config.getInt("http.port"), future.completer());

    return future;
}
 
開發者ID:docker-production-aws,項目名稱:microtrader,代碼行數:26,代碼來源:AuditVerticle.java

示例10: startHttpServer

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
private Future<HttpServer> startHttpServer() {
    Future<HttpServer> webServerFuture = Future.future();
    Future<Void> routerFuture = Future.future();
    Router router = configureRouter(routerFuture);

    routerFuture.compose(i -> {
        HttpServerOptions httpOptions = configureWebServer();
        int port = config.getPort();
        LOG.info("Starting web server on port {}", port);
        server = vertx.createHttpServer(httpOptions)
                .requestHandler(router::accept)
                .listen(port, webServerFuture);
    }, webServerFuture);

    return webServerFuture;
}
 
開發者ID:Deutsche-Boerse-Risk,項目名稱:DAVe,代碼行數:17,代碼來源:ApiVerticle.java

示例11: testValidJWT

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
@Test
public void testValidJWT(TestContext context) throws URISyntaxException {
    HttpServer openIdMockServer = this.createOpenIdMockServer(CERTS_VALID);
    Async openIdStarted = context.async();
    openIdMockServer.listen(TestConfig.OPENID_PORT, context.asyncAssertSuccess(i -> openIdStarted.complete()));
    openIdStarted.awaitSuccess(5000);
    JsonObject config = TestConfig.getApiConfig();
    config.getJsonObject("auth").put("enable", true);
    deployApiVerticle(context, config);

    createSslRequest("/api/v1.0/pr/latest")
            .putHeader("Authorization", "Bearer " + JWT_TOKEN)
            .send(context.asyncAssertSuccess(res ->
                    context.assertEquals(200, res.statusCode())
            ));
    openIdMockServer.close(context.asyncAssertSuccess());
}
 
開發者ID:Deutsche-Boerse-Risk,項目名稱:DAVe,代碼行數:18,代碼來源:AuthTest.java

示例12: bindSecureHttpServer

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
private Future<HttpServer> bindSecureHttpServer(final Router router) {

        if (isSecurePortEnabled()) {
            Future<HttpServer> result = Future.future();
            final String bindAddress = server == null ? getConfig().getBindAddress() : "?";
            if (server == null) {
                server = vertx.createHttpServer(getHttpServerOptions());
            }
            server.requestHandler(router::accept).listen(done -> {
                if (done.succeeded()) {
                    LOG.info("secure http server listening on {}:{}", bindAddress, server.actualPort());
                    result.complete(done.result());
                } else {
                    LOG.error("error while starting up secure http server", done.cause());
                    result.fail(done.cause());
                }
            });
            return result;
        } else {
            return Future.succeededFuture();
        }
    }
 
開發者ID:eclipse,項目名稱:hono,代碼行數:23,代碼來源:AbstractVertxBasedHttpProtocolAdapter.java

示例13: bindInsecureHttpServer

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
private Future<HttpServer> bindInsecureHttpServer(final Router router) {

        if (isInsecurePortEnabled()) {
            Future<HttpServer> result = Future.future();
            final String bindAddress = insecureServer == null ? getConfig().getInsecurePortBindAddress() : "?";
            if (insecureServer == null) {
                insecureServer = vertx.createHttpServer(getInsecureHttpServerOptions());
            }
            insecureServer.requestHandler(router::accept).listen(done -> {
                if (done.succeeded()) {
                    LOG.info("insecure http server listening on {}:{}", bindAddress, insecureServer.actualPort());
                    result.complete(done.result());
                } else {
                    LOG.error("error while starting up insecure http server", done.cause());
                    result.fail(done.cause());
                }
            });
            return result;
        } else {
            return Future.succeededFuture();
        }
    }
 
開發者ID:eclipse,項目名稱:hono,代碼行數:23,代碼來源:AbstractVertxBasedHttpProtocolAdapter.java

示例14: testStartUsesClientProvidedHttpServer

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
/**
 * Verifies that a client provided http server is started instead of creating and starting a new http server.
 * 
 * @param ctx The helper to use for running async tests on vertx.
 * @throws Exception if the test fails.
 */
@SuppressWarnings("unchecked")
@Test
public void testStartUsesClientProvidedHttpServer(final TestContext ctx) throws Exception {

    // GIVEN an adapter with a client provided http server
    HttpServer server = getHttpServer(false);
    AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null);
    adapter.setCredentialsAuthProvider(credentialsAuthProvider);

    // WHEN starting the adapter
    Async startup = ctx.async();
    Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertSuccess(s -> {
        startup.complete();
    }));
    adapter.start(startupTracker);

    // THEN the client provided http server has been configured and started
    startup.await();
    verify(server).requestHandler(any(Handler.class));
    verify(server).listen(any(Handler.class));
    verify(messagingClient).connect(any(ProtonClientOptions.class), any(Handler.class), any(Handler.class));
    verify(registrationClient).connect(any(ProtonClientOptions.class), any(Handler.class), any(Handler.class));
}
 
開發者ID:eclipse,項目名稱:hono,代碼行數:31,代碼來源:AbstractVertxBasedHttpProtocolAdapterTest.java

示例15: testStartInvokesOnStartupSuccess

import io.vertx.core.http.HttpServer; //導入依賴的package包/類
/**
 * Verifies that the <me>onStartupSuccess</em> method is invoked if the http server has been started successfully.
 * 
 * @param ctx The helper to use for running async tests on vertx.
 * @throws Exception if the test fails.
 */
@Test
public void testStartInvokesOnStartupSuccess(final TestContext ctx) throws Exception {

    // GIVEN an adapter with a client provided http server
    HttpServer server = getHttpServer(false);
    Async onStartupSuccess = ctx.async();

    AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, s -> onStartupSuccess.complete());
    adapter.setCredentialsAuthProvider(credentialsAuthProvider);
    adapter.setMetrics(mock(HttpAdapterMetrics.class));

    // WHEN starting the adapter
    Async startup = ctx.async();
    Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertSuccess(s -> {
        startup.complete();
    }));
    adapter.start(startupTracker);

    // THEN the onStartupSuccess method has been invoked
    startup.await();
    onStartupSuccess.await();
}
 
開發者ID:eclipse,項目名稱:hono,代碼行數:30,代碼來源:AbstractVertxBasedHttpProtocolAdapterTest.java


注:本文中的io.vertx.core.http.HttpServer類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。