当前位置: 首页>>代码示例>>Java>>正文


Java Router.router方法代码示例

本文整理汇总了Java中io.vertx.rxjava.ext.web.Router.router方法的典型用法代码示例。如果您正苦于以下问题:Java Router.router方法的具体用法?Java Router.router怎么用?Java Router.router使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.vertx.rxjava.ext.web.Router的用法示例。


在下文中一共展示了Router.router方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start(Future<Void> future) throws Exception {
  super.start();
  // TODO: 21.08.2017 use circuit breaker etc..
  String host = config().getString("http.host", "localhost");
  int port = config().getInteger("http.port", 8080);

  Router router = Router.router(vertx);
  enableLocalSession(router);
  router.route().handler(BodyHandler.create());
  router.get("/api/v").handler(this::apiVersion);

  // TODO: 23.08.2017 pac4j auth handlers

  // TODO: 23.08.2017 login, logout, auth callback, eventbus, etc..

  router.route("/api/*").handler(this::dispatchRequests);
  router.route("/*").handler(Status::notFound);

  // TODO: 23.08.2017 https? -> only if used without nginx

  createHttpServer(router, host, port)
      .flatMap(v -> publishApiGateway(host, port))
      .subscribe(toSubscriber(future));
}
 
开发者ID:kristenkotkas,项目名称:moviediary,代码行数:26,代码来源:GatewayVerticle.java

示例2: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start(Future<Void> future) throws Exception {

    Router router = Router.router(vertx);

    circuit = CircuitBreaker.create("circuit-breaker", vertx, new CircuitBreakerOptions()
        .setFallbackOnFailure(true)
        .setMaxFailures(3)
        .setResetTimeout(5000)
        .setTimeout(1000)
    );

    router.get("/").handler(this::getShoppingList);

    ServiceDiscovery.create(vertx, discovery -> {

        Single<WebClient> s1 = HttpEndpoint.rxGetWebClient(discovery,
            rec -> rec.getName().equals("shopping-backend"));
        Single<WebClient> s2 = HttpEndpoint.rxGetWebClient(discovery,
            rec -> rec.getName().equals("pricer-service"));

        Single.zip(s1, s2, (x, y) -> {
            shopping = x;
            pricer = y;
            return vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(8080);
        }).subscribe();
    });

}
 
开发者ID:cescoffier,项目名称:vertx-chtijug-2017,代码行数:32,代码来源:MyShoppingList.java

示例3: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start() {
    circuit = CircuitBreaker.create("circuit-breaker", vertx,
        new CircuitBreakerOptions()
            .setFallbackOnFailure(true)
            .setMaxFailures(3)
            .setResetTimeout(5000)
            .setTimeout(1000)
    );


    Router router = Router.router(vertx);
    router.route("/health").handler(rc ->
        rc.response().end("OK"));
    router.route("/").handler(this::getShoppingList);

    ServiceDiscovery.create(vertx, discovery -> {
        // Get pricer-service
        Single<WebClient> s1 = HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("pricer-service"));

        // Get shopping-backend
        Single<WebClient> s2 = HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("shopping-backend"));

        Single.zip(s1, s2, (p, s) -> {
            pricer = p;
            shopping = s;

            return vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(8080);
        }).subscribe();

        // When both are done...

    });
}
 
开发者ID:cescoffier,项目名称:vertx-chtijug-2017,代码行数:37,代码来源:MyShoppingList.java

示例4: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start() {
    circuit = CircuitBreaker.create("circuit-breaker", vertx,
        new CircuitBreakerOptions()
            .setFallbackOnFailure(true)
            .setMaxFailures(3)
            .setResetTimeout(5000)
            .setTimeout(1000)
    );

    Router router = Router.router(vertx);
    router.route("/health").handler(rc -> rc.response().end("OK"));
    router.route("/").handler(this::getShoppingList);

    ServiceDiscovery.create(vertx, discovery -> {
        // Get pricer-service
        Single<WebClient> s1 = HttpEndpoint.rxGetWebClient(discovery,
            svc -> svc.getName().equals("pricer-service"));

        // Get shopping-backend
        Single<WebClient> s2 = HttpEndpoint.rxGetWebClient(discovery,
            svc -> svc.getName().equals("shopping-backend"));

        // When both are done...
        Single.zip(s1, s2, (p, s) -> {
            pricer = p;
            shopping = s;

            return vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(8080);
        })
            .subscribe();
    });


}
 
开发者ID:cescoffier,项目名称:vertx-rhsummit-2017,代码行数:38,代码来源:MyShoppingList.java

示例5: startVertx

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
private Single<Void> startVertx(JsonObject config, VertxResteasyDeployment deployment) {
	Router router = Router.router(vertx);
	AppGlobals.get().setRouter(router);
	
	VertxPluginRequestHandler resteasyHandler = new VertxPluginRequestHandler(vertx, deployment, plugins);
	
	return doOnPlugins(plugin -> plugin.preRoute())
			.map(v -> {
				setupRoutes(router);
				router.route().handler(routingContext -> {
					ResteasyProviderFactory.pushContext(RoutingContext.class, routingContext);
					resteasyHandler.handle(routingContext.request());
				});
				return null;
			}).flatMap(v -> doOnPlugins(plugin -> plugin.postRoute()))
			.flatMap(v -> {
				return Single.<Void>create(sub -> {
					// Start the front end server using the Jax-RS controller
					vertx.createHttpServer()
					.requestHandler(router::accept)
					.listen(config.getInteger("http_port", 9000), ar -> {
						if(ar.failed()){
							ar.cause().printStackTrace();
							sub.onError(ar.cause());
						}else {
							System.out.println("Server started on port "+ ar.result().actualPort());
							sub.onSuccess(null);
						}
					});
				});
			});
}
 
开发者ID:FroMage,项目名称:redpipe,代码行数:33,代码来源:Server.java

示例6: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
/**
 * Creates service for interacting with database.
 * Creates service for interacting with TheMovieDatabase API.
 * Creates service for interacting with bankLink application.
 * Creates service for interacting with mail server.
 * Creates Pac4j security engine configuration.
 * <p>
 * Creates authentication for routes.
 * Creates external API for TheMovieDatabase services.
 * Creates external API for bankLink services.
 * Creates Eventbus (aka Websocket for browsers) addresses for various services.
 * Creates external API for database services.
 * Creates external API for mail services.
 * Creates routes for UI rendering.
 * <p>
 * Starts the HTTP server.
 */
@Override
public void start(Future<Void> future) throws Exception {
  Router router = Router.router(vertx);
  database = createIfMissing(database, () -> DatabaseService.create(vertx, config()));
  tmdb = createIfMissing(tmdb, () -> TmdbService.create(vertx, config(), database));
  omdb = createIfMissing(omdb, () -> OmdbService.create(vertx, config(), database));
  bankLink = createIfMissing(bankLink, () -> BankLinkService.create(vertx, config()));
  mail = createIfMissing(mail, () -> MailService.create(vertx, database));
  recommend = createIfMissing(recommend, () -> RecommendService.create(vertx));
  securityConfig = createIfMissing(securityConfig, () -> new SecurityConfig(vertx, config(), database));
  Arrays.asList(
      new AuthRouter(vertx, config(), securityConfig),
      new TmdbRouter(vertx, tmdb),
      new OmdbRouter(vertx, omdb),
      new BankLinkRouter(vertx, bankLink),
      new DatabaseRouter(vertx, config(), securityConfig, database, mail),
      new MailRouter(vertx, mail),
      new RecommendRouter(recommend),
      new UiRouter(vertx, securityConfig)).forEach(routable -> routable.route(router));
  startEventbus(router, vertx);
  vertx.createHttpServer(new HttpServerOptions()
      .setCompressionSupported(true)
      .setCompressionLevel(3))
      .requestHandler(router::accept)
      .rxListen(config().getInteger(HTTP_PORT, DEFAULT_PORT), config().getString(HTTP_HOST, DEFAULT_HOST))
      .subscribe(res -> future.complete(), future::fail);
}
 
开发者ID:kristenkotkas,项目名称:moviediary,代码行数:45,代码来源:ServerVerticle.java

示例7: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start() {
  // Create a router object.
  Router router = Router.router(vertx);
  // enable parsing of request bodies
  router.route().handler(BodyHandler.create());
  // perform validation of the :id parameter
  router.route("/api/fruits/:id")
      .handler(this::validateId);
  // implement a basic REST CRUD mapping
  router.get("/api/fruits").handler(this::retrieveAll);
  router.post("/api/fruits").handler(this::addOne);
  router.get("/api/fruits/:id").handler(this::getOne);
  router.put("/api/fruits/:id").handler(this::updateOne);
  router.delete("/api/fruits/:id").handler(this::deleteOne);

  // health check
  router.get("/health").handler(rc -> rc.response().end("OK"));
  // web interface
  router.get().handler(StaticHandler.create());


  // Create a JDBC client
  JDBCClient jdbc = JDBCClient.createShared(vertx, new JsonObject()
    .put("url", "jdbc:postgresql://" + getEnv("MY_DATABASE_SERVICE_HOST", "localhost") + ":5432/my_data")
    .put("driver_class", "org.postgresql.Driver")
    .put("user", getEnv("DB_USERNAME", "user"))
    .put("password", getEnv("DB_PASSWORD", "password"))
  );

  DBInitHelper.initDatabase(vertx, jdbc)
    .andThen(initHttpServer(router, jdbc))
    .subscribe(
      (http) -> System.out.println("Server ready on port " + http.actualPort()),
      Throwable::printStackTrace
    );
}
 
开发者ID:cescoffier,项目名称:various-vertx-demos,代码行数:38,代码来源:CrudApplication.java

示例8: init

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void init(BundleContext arg0, DependencyManager dm) throws Exception {
	vertx = Vertx.vertx();
	
	dm.add(createComponent().setInterface(Vertx.class.getName(), null).setImplementation(vertx));
	dm.add(createComponent().setInterface(EventBus.class.getName(), null).setImplementation(vertx.eventBus()));
	
	Router router = Router.router(vertx);
	dm.add(createComponent().setInterface(Router.class.getName(), null).setImplementation(router));
}
 
开发者ID:paulbakker,项目名称:osgi-vertx-demo,代码行数:11,代码来源:VertxActivator.java

示例9: configureTheHTTPServer

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
private Single<HttpServer> configureTheHTTPServer() {
  //----
  // Use a Vert.x Web router for this REST API.
  Router router = Router.router(vertx);
  router.get("/").handler(this::retrieveOperations);
  HttpServer server = vertx.createHttpServer().requestHandler(router::accept);
  Integer port = config().getInteger("http.port", 0);
  return server.rxListen(port);
  //----
}
 
开发者ID:cescoffier,项目名称:vertx-microservices-workshop,代码行数:11,代码来源:AuditVerticle.java

示例10: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start() throws Exception {
    Router router = Router.router(vertx);

    router.get("/hello").handler(routingContext -> {
        HttpServerRequest request = routingContext.request();
        HttpServerResponse response = routingContext.response();

        Long minSleep = (request.getParam("minSleepMs") != null) ? Long.parseLong(request.getParam("minSleepMs")) : 500L;
        Long maxSleep = (request.getParam("maxSleepMs") != null) ? Long.parseLong(request.getParam("maxSleepMs")) : 500L;

        HelloGenerator helloTask = new HelloGenerator(minSleep, maxSleep);

        Observable.<String>create(sub -> {
            String message = null;
            try {
                message = helloTask.call();
            } catch (Exception e) {
                sub.onError(e);
            }
            sub.onNext(message);
            sub.onCompleted();
        })
        .last()
        .subscribeOn(Schedulers.io())
        .subscribe(message -> routingContext.response().setStatusCode(200).end(message),
                   error -> routingContext.response().setStatusCode(500).end());
    });

    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
 
开发者ID:gregwhitaker,项目名称:async-showdown,代码行数:32,代码来源:Application.java

示例11: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start(Future<Void> startFuture) throws Exception {

  String wikiDbQueue = config().getString(CONFIG_WIKIDB_QUEUE, "wikidb.queue");
  dbService = io.vertx.guides.wiki.database.WikiDatabaseService.createProxy(vertx.getDelegate(), wikiDbQueue);

  HttpServer server = vertx.createHttpServer();

  Router router = Router.router(vertx);

  router.route().handler(CookieHandler.create());
  router.route().handler(BodyHandler.create());
  router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));

  // tag::sockjs-handler-setup[]
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx); // <1>
  BridgeOptions bridgeOptions = new BridgeOptions()
    .addInboundPermitted(new PermittedOptions().setAddress("app.markdown"))  // <2>
    .addOutboundPermitted(new PermittedOptions().setAddress("page.saved")); // <3>
  sockJSHandler.bridge(bridgeOptions); // <4>
  router.route("/eventbus/*").handler(sockJSHandler); // <5>
  // end::sockjs-handler-setup[]

  // tag::eventbus-markdown-consumer[]
  vertx.eventBus().<String>consumer("app.markdown", msg -> {
    String html = Processor.process(msg.body());
    msg.reply(html);
  });
  // end::eventbus-markdown-consumer[]

  router.get("/app/*").handler(StaticHandler.create().setCachingEnabled(false));
  router.get("/").handler(context -> context.reroute("/app/index.html"));

  router.get("/api/pages").handler(this::apiRoot);
  router.get("/api/pages/:id").handler(this::apiGetPage);
  router.post().handler(BodyHandler.create());
  router.post("/api/pages").handler(this::apiCreatePage);
  router.put().handler(BodyHandler.create());
  router.put("/api/pages/:id").handler(this::apiUpdatePage);
  router.delete("/api/pages/:id").handler(this::apiDeletePage);

  int portNumber = config().getInteger(CONFIG_HTTP_SERVER_PORT, 8080);
  server
    .requestHandler(router::accept)
    .rxListen(portNumber)
    .subscribe(s -> {
      LOGGER.info("HTTP server running on port " + portNumber);
      startFuture.complete();
    }, t -> {
      LOGGER.error("Could not start a HTTP server", t);
      startFuture.fail(t);
    });
}
 
开发者ID:vert-x3,项目名称:vertx-guide-for-java-devs,代码行数:54,代码来源:HttpServerVerticle.java

示例12: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start(Future<Void> startFuture) throws Exception {

  String wikiDbQueue = config().getString(CONFIG_WIKIDB_QUEUE, "wikidb.queue");
  dbService = io.vertx.guides.wiki.database.WikiDatabaseService.createProxy(vertx.getDelegate(), wikiDbQueue);

  HttpServer server = vertx.createHttpServer();

  Router router = Router.router(vertx);

  router.route().handler(CookieHandler.create());
  router.route().handler(BodyHandler.create());
  router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));

  // tag::static-assets[]
  router.get("/app/*").handler(StaticHandler.create().setCachingEnabled(false)); // <1> <2>
  router.get("/").handler(context -> context.reroute("/app/index.html"));
  // end::static-assets[]

  // tag::preview-rendering[]
  router.post("/app/markdown").handler(context -> {
    String html = Processor.process(context.getBodyAsString());
    context.response()
      .putHeader("Content-Type", "text/html")
      .setStatusCode(200)
      .end(html);
  });
  // end::preview-rendering[]

  // tag::routes[]
  router.get("/api/pages").handler(this::apiRoot);
  router.get("/api/pages/:id").handler(this::apiGetPage);
  router.post().handler(BodyHandler.create());
  router.post("/api/pages").handler(this::apiCreatePage);
  router.put().handler(BodyHandler.create());
  router.put("/api/pages/:id").handler(this::apiUpdatePage);
  router.delete("/api/pages/:id").handler(this::apiDeletePage);
  // end::routes[]

  int portNumber = config().getInteger(CONFIG_HTTP_SERVER_PORT, 8080);
  server
    .requestHandler(router::accept)
    .rxListen(portNumber)
    .subscribe(s -> {
      LOGGER.info("HTTP server running on port " + portNumber);
      startFuture.complete();
    }, t -> {
      LOGGER.error("Could not start a HTTP server", t);
      startFuture.fail(t);
    });
}
 
开发者ID:vert-x3,项目名称:vertx-guide-for-java-devs,代码行数:52,代码来源:HttpServerVerticle.java

示例13: start

import io.vertx.rxjava.ext.web.Router; //导入方法依赖的package包/类
@Override
public void start() throws Exception {

	Injector injector = Guice.createInjector(new LoggerModule(),
												new AopModule(),
												new ContextModule(),
												new HandlerModule(),
												new ServiceModule()
								);

	// URL routing
	Router router = Router.router(vertx);

	router.options("/*")
			.handler(context -> {
				context.response()
						.putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
						.putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*")
						.putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "*")
						.setStatusCode(200)
						.end();
			});

	router.get("/")
			.handler(context -> {
				context.response()
						.setStatusCode(303)
						.putHeader(HttpHeaders.LOCATION, "/alive")
						.end();
			});

	router.get("/hello")
			.handler(context -> {
				JsonObject json = new JsonObject().put("message",
														"Hello! Vert.x 3.x JSON");

				Buffer buffer = Buffer.buffer(json.toString());

				context.response()
						.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
						.putHeader(HttpHeaders.CONTENT_LENGTH, Objects.toString(buffer.length()))
						.write(buffer)
						.end();
			});

	router.get("/alive")
			.handler(injector.getInstance(AliveHandler.class));

	HttpServerOptions serverOption = new HttpServerOptions().setAcceptBacklog(10000)
															.setCompressionSupported(true);
	HttpServer server = vertx.createHttpServer(serverOption);

	server.requestHandler(router::accept)
			.listenObservable(8080)
			.subscribe(result -> logger.info("start.server"),
						error -> logger.error("failed.start.server"),
						() -> logger.info("complete.ini.server"));

	// server.requestStream()
	// .toObservable()
	// .subscribe(req -> {
	// req.response()
	// .putHeader("content-type", "text/html")
	// .end("<html><body><h1>Hello from vert.x!</h1></body></html>");
	// });
}
 
开发者ID:takecy,项目名称:vertx3-api-server,代码行数:67,代码来源:HttpVerticle.java


注:本文中的io.vertx.rxjava.ext.web.Router.router方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。