org.springframework.web.reactive.function.server.RouterFunctions Java Examples

The following examples show how to use org.springframework.web.reactive.function.server.RouterFunctions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultRouterFunctionSpecTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void exceptionHandler() {

	RouterFunction<ServerResponse> routerFunction = RouterFunctions.route()
			.GET("/error", request -> Mono.error(new IllegalStateException("boo")))
			.build();

	new DefaultRouterFunctionSpec(routerFunction)
			.handlerStrategies(HandlerStrategies.builder()
					.exceptionHandler((exchange, ex) -> {
						exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
						return Mono.empty();
					})
					.build())
			.build()
			.get()
			.uri("/error")
			.exchange()
			.expectStatus().isBadRequest();
}
 
Example #2
Source File: Router.java    From influx-proxy with Apache License 2.0 6 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> routeCity(InfluxProxyHandler influxProxyHandler) {
    return RouterFunctions
            .route(RequestPredicates.path("/query")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::query)
            .andRoute(RequestPredicates.POST("/write")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::write)
            .andRoute(RequestPredicates.GET("/ping")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::ping)
            .andRoute(RequestPredicates.path("/debug/{opt}")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::debug)
            .andRoute(RequestPredicates.path("/debug")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::debug)
            .andRoute(RequestPredicates.path("/refresh/allBackend")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::refreshAllBackend)
            ;
}
 
Example #3
Source File: Chapter7SpringDataWebFluxIntegrationApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> routerFunction(
   ChatHandler chatHandler
  ) {
	return RouterFunctions
		.route(
			GET("/"),
			serverRequest -> ServerResponse
				.ok()
				.contentType(MediaType.APPLICATION_STREAM_JSON)
				.body(chatHandler
                 .messageStream(), Message.class))
        .andRoute(
           GET("/{user}"),
           serverRequest -> {
              String user = serverRequest.pathVariable("user");
              return ServerResponse
                 .ok()
                 .contentType(MediaType.APPLICATION_STREAM_JSON)
                 .body(chatHandler
                    .messageStreamForUser(user), Message.class);
           });
}
 
Example #4
Source File: FunctionalWebApplication.java    From tutorials with MIT License 6 votes vote down vote up
private RouterFunction<ServerResponse> routingFunction() {
    FormHandler formHandler = new FormHandler();

    RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
        .doOnNext(actors::add)
        .then(ok().build()));

    return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
        .andRoute(POST("/upload"), formHandler::handleUpload)
        .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
        .andNest(path("/actor"), restfulRouter)
        .filter((request, next) -> {
            System.out.println("Before handler invocation: " + request.path());
            return next.handle(request);
        });
}
 
Example #5
Source File: RouterFunctionMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void setAttributes(Map<String, Object> attributes, ServerRequest serverRequest,
		HandlerFunction<?> handlerFunction) {

	attributes.put(RouterFunctions.REQUEST_ATTRIBUTE, serverRequest);
	attributes.put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerFunction);

	PathPattern matchingPattern =
			(PathPattern) attributes.get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE);
	if (matchingPattern != null) {
		attributes.put(BEST_MATCHING_PATTERN_ATTRIBUTE, matchingPattern);
	}
	Map<String, String> uriVariables =
			(Map<String, String>) attributes
					.get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	if (uriVariables != null) {
		attributes.put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
	}
}
 
Example #6
Source File: PositionRouter.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@Bean
@RouterOperations({ @RouterOperation(path = "/getAllPositions", operation = @Operation(description = "Get all positions", operationId = "findAll",tags = "positions",
		responses = @ApiResponse(responseCode = "200", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Position.class)))))),
		@RouterOperation(path = "/getPosition/{id}", operation = @Operation(description = "Find all", operationId = "findById", tags = "positions",parameters = @Parameter(name = "id", in = ParameterIn.PATH),
				 responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Position.class))))),
		@RouterOperation(path = "/createPosition",  operation = @Operation(description = "Save position", operationId = "save", tags = "positions",requestBody = @RequestBody(content = @Content(schema = @Schema(implementation = Position.class))),
				responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Position.class))))),
		@RouterOperation(path = "/deletePosition/{id}", operation = @Operation(description = "Delete By Id", operationId = "deleteBy",tags = "positions", parameters = @Parameter(name = "id", in = ParameterIn.PATH),
				responses = @ApiResponse(responseCode = "200", content = @Content)))})
public RouterFunction<ServerResponse> positionRoute(PositionHandler handler) {
	return RouterFunctions
			.route(GET("/getAllPositions").and(accept(MediaType.APPLICATION_JSON)), handler::findAll)
			.andRoute(GET("/getPosition/{id}").and(accept(MediaType.APPLICATION_STREAM_JSON)), handler::findById)
			.andRoute(POST("/createPosition").and(accept(MediaType.APPLICATION_JSON)), handler::save)
			.andRoute(DELETE("/deletePosition/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::delete);
}
 
Example #7
Source File: FunctionalWebApplication.java    From tutorials with MIT License 6 votes vote down vote up
private RouterFunction<ServerResponse> routingFunction() {
    FormHandler formHandler = new FormHandler();

    RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
        .doOnNext(actors::add)
        .then(ok().build()));

    return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
        .andRoute(POST("/upload"), formHandler::handleUpload)
        .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
        .andNest(path("/actor"), restfulRouter)
        .filter((request, next) -> {
            System.out.println("Before handler invocation: " + request.path());
            return next.handle(request);
        });
}
 
Example #8
Source File: DefaultRouterFunctionSpecTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void exceptionHandler() {

	RouterFunction<ServerResponse> routerFunction = RouterFunctions.route()
			.GET("/error", request -> Mono.error(new IllegalStateException("boo")))
			.build();

	new DefaultRouterFunctionSpec(routerFunction)
			.handlerStrategies(HandlerStrategies.builder()
					.exceptionHandler((exchange, ex) -> {
						exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
						return Mono.empty();
					})
					.build())
			.build()
			.get()
			.uri("/error")
			.exchange()
			.expectStatus().isBadRequest();
}
 
Example #9
Source File: StudentCompositeRoutes.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
@Bean
RouterFunction<ServerResponse> compositeRoutes(){

	RouterFunction<ServerResponse> studentResponse =
			RouterFunctions.route(RequestPredicates.
					GET("/api/f/composite/getStudent/{rollNo}"),
					serverRequest -> {
						int rollNo = getInt(serverRequest.pathVariable("rollNo"));
						return ServerResponse.ok().
								body(studentMongoRepository.
										findByRollNo(rollNo), Student.class);
					})
			.and(
					RouterFunctions.route(RequestPredicates.
							GET("/api/f/composite/getAllStudent"),
							serverRequest -> 
					ServerResponse.ok().
					body(studentMongoRepository.findAll(), Student.class))
					);

	return studentResponse;
}
 
Example #10
Source File: FunctionalSpringBootApplication.java    From tutorials with MIT License 6 votes vote down vote up
private RouterFunction<ServerResponse> routingFunction() {
    FormHandler formHandler = new FormHandler();

    RouterFunction<ServerResponse> restfulRouter = route(GET("/"),
        serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"),
            serverRequest -> serverRequest.bodyToMono(Actor.class)
                .doOnNext(actors::add)
                .then(ok().build()));

    return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
        .andRoute(POST("/login"), formHandler::handleLogin)
        .andRoute(POST("/upload"), formHandler::handleUpload)
        .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
        .andNest(path("/actor"), restfulRouter)
        .filter((request, next) -> {
            System.out.println("Before handler invocation: " + request.path());
            return next.handle(request);
        });
}
 
Example #11
Source File: QuoteRouter.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@RouterOperations({
		@RouterOperation(path = "/hello", operation = @Operation(operationId = "hello", responses = @ApiResponse(responseCode = "200"))),
		@RouterOperation(path = "/echo", produces = TEXT_PLAIN_VALUE, operation = @Operation(operationId = "echo", requestBody = @RequestBody(content = @Content(schema = @Schema(type = "string"))),
				responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(type = "string"))))),
		@RouterOperation(path = "/echo",produces = APPLICATION_JSON_VALUE,  operation = @Operation(operationId = "echo", requestBody = @RequestBody(content = @Content(schema = @Schema(type = "string"))),
				responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(type = "string"))))),
		@RouterOperation(path = "/quotes", produces = APPLICATION_JSON_VALUE, operation = @Operation(operationId = "fetchQuotes", parameters = @Parameter(name = "size", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
				responses = @ApiResponse(responseCode = "200", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Quote.class)))))),
		@RouterOperation(path = "/quotes", produces = APPLICATION_STREAM_JSON_VALUE, operation = @Operation(operationId = "fetchQuotes",
				responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Quote.class))))) })
@Bean
public RouterFunction<ServerResponse> route(QuoteHandler quoteHandler) {
	return RouterFunctions
			.route(GET("/hello").and(accept(TEXT_PLAIN)), quoteHandler::hello)
			.andRoute(POST("/echo").and(accept(TEXT_PLAIN).and(contentType(TEXT_PLAIN))), quoteHandler::echo)
			.andRoute(POST("/echo").and(accept(APPLICATION_JSON).and(contentType(APPLICATION_JSON))), quoteHandler::echo)
			.andRoute(GET("/quotes").and(accept(APPLICATION_JSON)), quoteHandler::fetchQuotes)
			.andRoute(GET("/quotes").and(accept(APPLICATION_STREAM_JSON)), quoteHandler::streamQuotes);
}
 
Example #12
Source File: EmployeeRouter.java    From webflux-rxjava2-jdbc-example with Apache License 2.0 6 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> route(EmployeeHandler handler) {
  return RouterFunctions.route(
          GET("/employees").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
          handler::getAllEmployees)
      .andRoute(
          GET("/employee/fn/{fn}/ln/{ln}")
              .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
          handler::getEmployee)
      .andRoute(
          PUT("/employee").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
          handler::createNewEmployee)
      .andRoute(
          DELETE("/employee/id/{id}").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
          handler::deleteEmployee)
      .andRoute(
          GET("/departments").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
          handler::getAllDepartments);
}
 
Example #13
Source File: StandaloneApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
public static void main(String... args) {
    long start = System.currentTimeMillis();
    HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes(
        new BCryptPasswordEncoder(18)
    ));
    ReactorHttpHandlerAdapter reactorHttpHandler = new ReactorHttpHandlerAdapter(httpHandler);

    DisposableServer server = HttpServer.create()
                                        .host("localhost")
                                        .port(8080)
                                        .handle(reactorHttpHandler)
                                        .bindNow();

    LOGGER.debug("Started in " + (System.currentTimeMillis() - start) + " ms");

    server.onDispose()
          .block();
}
 
Example #14
Source File: HttpServerConfig.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public ServletRegistrationBean routeServlet1(RouterFunction<?> routerFunction) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction );
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);

     ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(servlet, "/flux" + "/*");
     registrationBean.setLoadOnStartup(1);
     registrationBean.setAsyncSupported(true);
     
 	System.out.println("starts server");		
     return registrationBean;
 }
 
Example #15
Source File: RouterFunctionConfiguration.java    From micro-service with MIT License 5 votes vote down vote up
@Bean
@Autowired
public RouterFunction<ServerResponse> listUsers(UserRepository userRepository) {
    return RouterFunctions.route(RequestPredicates.GET("/users"),
            request -> {
                Collection<User> users = userRepository.list();
                Flux<User> userFlux = Flux.fromIterable(users);
                return ServerResponse.ok().body(userFlux, User.class);
            });
}
 
Example #16
Source File: HttpServerConfig.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public ServletRegistrationBean routeServlet1(RouterFunction<?> routerFunction) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction );
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);

     ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(servlet, "/flux" + "/*");
     registrationBean.setLoadOnStartup(1);
     registrationBean.setAsyncSupported(true);
     
 	System.out.println("starts server");		
     return registrationBean;
 }
 
Example #17
Source File: BootWebfluxApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
  return RouterFunctions
      .route(RequestPredicates.GET("/hello")
              .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
          greetingHandler::hello);
}
 
Example #18
Source File: ReactiveSecurityApplication.java    From training with Apache License 2.0 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> routes() {
	return RouterFunctions
			.route(GET("/greeting"),
					request ->
							ok().body(
									request
											.principal()
											.map(Principal::getName)
											.map(name -> "Hello, " + name + "!"), String.class))
			.andRoute(GET("/hi/{name}"), req -> ok().body(Flux.just("Hello, " + req.pathVariable("name") + "!"), String.class));
}
 
Example #19
Source File: Spring5ReactiveServerClientIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeAll
public static void setUp() throws Exception {
    HttpServer server = HttpServer.create()
        .host("localhost")
        .port(8080);
    RouterFunction<?> route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok()
        .body(request.bodyToFlux(Task.class)
            .map(ll -> new Task("TaskName", 1)), Task.class))
        .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok()
            .body(Mono.just("server is alive"), String.class)));
    HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
    ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
    disposableServer = server.handle(adapter)
        .bindNow();
}
 
Example #20
Source File: ValidationsRouters.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> validationsRouter(@Autowired CustomRequestEntityValidationHandler dryHandler,
    @Autowired FunctionalHandler complexHandler,
    @Autowired OtherEntityValidationHandler otherHandler,
    @Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) {
    return RouterFunctions.route(RequestPredicates.POST("/complex-handler-functional-validation"), complexHandler::handleRequest)
        .andRoute(RequestPredicates.POST("/dry-functional-validation"), dryHandler::handleRequest)
        .andRoute(RequestPredicates.POST("/other-dry-functional-validation"), otherHandler::handleRequest)
        .andRoute(RequestPredicates.POST("/annotated-functional-validation"), annotatedEntityHandler::handleRequest);
}
 
Example #21
Source File: MetricsConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("exporter"))) {
        return;
    }

    applicationContext.registerBean(MetricsCollector.class);

    applicationContext.registerBean("prometheus", RouterFunction.class, () -> {
        var metricsCollector = applicationContext.getBean(MetricsCollector.class);
        return RouterFunctions.route()
                .GET("/prometheus", __ -> {
                    return metricsCollector.collect()
                            .collectList()
                            .flatMap(metrics -> {
                                try {
                                    var writer = new StringWriter();
                                    TextFormat.write004(writer, Collections.enumeration(metrics));
                                    return ServerResponse.ok()
                                            .contentType(MediaType.valueOf(TextFormat.CONTENT_TYPE_004))
                                            .bodyValue(writer.toString());
                                } catch (IOException e) {
                                    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                                }
                            });
                })
                .build();

    });
}
 
Example #22
Source File: Chapter5ReactiveApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> routerFunction(
	SensorReadingRepository sensorReadingRepository
) {
	return RouterFunctions
		.route(
			GET("/"),
			serverRequest -> ServerResponse
				.ok()
				.contentType(MediaType.APPLICATION_STREAM_JSON)
				.body(sensorReadingRepository.findBy(), SensorsReadings.class));
}
 
Example #23
Source File: StudentRouterHandlerCombined.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> returnAllStudentWithCombineFun(){
	
       HandlerFunction<ServerResponse> studentHandler = 
               serverRequest -> 
            	  ServerResponse.ok().body(studentMongoRepository.findAll(), Student.class);
	
	RouterFunction<ServerResponse> studentResponse =
   		RouterFunctions.route(RequestPredicates.GET("/api/f/combine/getAllStudent"),
   				studentHandler);
	
	return studentResponse;
   }
 
Example #24
Source File: HelloRouter.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> route(HelloHandler hander) {
	/**
	 * RouterFunctions:对请求路由处理类,即将请求路由到处理器。
	 * RouterFunctions.route(RequestPredicate, HandlerFunction) 方法,对应的入参是请求参数和处理函数,如果请求匹配,就调用对应的处理器函数。
	 * RequestPredicates.GET: 是将一个 GET 请求 /webflux/hello 路由到处理器 helloHandler 的 hello 方法上。跟 Spring MVC 模式下的 HandleMapping 的作用类似。
	
	 */
	
	RouterFunction<ServerResponse> routerFunction = RouterFunctions.route(
			RequestPredicates.GET("/webflux/hello").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
			hander::hello);

	return routerFunction;
}
 
Example #25
Source File: GatewaySampleApplication.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> testWhenMetricPathIsNotMeet() {
	RouterFunction<ServerResponse> route = RouterFunctions.route(
			RequestPredicates.path("/actuator/metrics/gateway.requests"),
			request -> ServerResponse.ok().body(BodyInserters
					.fromValue(HELLO_FROM_FAKE_ACTUATOR_METRICS_GATEWAY_REQUESTS)));
	return route;
}
 
Example #26
Source File: ExploreSpring5URLPatternUsingRouterFunctions.java    From tutorials with MIT License 5 votes vote down vote up
private RouterFunction<ServerResponse> routingFunction() {

        return route(GET("/p?ths"), serverRequest -> ok().body(fromObject("/p?ths"))).andRoute(GET("/test/{*id}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("id"))))
            .andRoute(GET("/*card"), serverRequest -> ok().body(fromObject("/*card path was accessed")))
            .andRoute(GET("/{var1}_{var2}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("var1") + " , " + serverRequest.pathVariable("var2"))))
            .andRoute(GET("/{baeldung:[a-z]+}"), serverRequest -> ok().body(fromObject("/{baeldung:[a-z]+} was accessed and baeldung=" + serverRequest.pathVariable("baeldung"))))
            .and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/")));
    }
 
Example #27
Source File: HttpServerConfig.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public ServletRegistrationBean routeServlet1(RouterFunction<?> routerFunction) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction );
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);

     ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(servlet, "/flux" + "/*");
     registrationBean.setLoadOnStartup(1);
     registrationBean.setAsyncSupported(true);
     
 	System.out.println("starts server");		
     return registrationBean;
 }
 
Example #28
Source File: ExportManageServerRunner.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
/**
 * 暴露6200管理端口
 */
@Override
public void run(ApplicationArguments args) throws Exception {
    RouterFunction manageRouterFunction = RouterFunctions
            .route(RequestPredicates.GET("/ok"), req -> {
                return ServerResponse.ok()
                        .syncBody("online");
            })
            .andRoute(RequestPredicates.GET("/cmd/{line}"), request -> {
                String pathVar = request.pathVariable("line");
                try {
                    if ("down".equals(pathVar)) {
                        refuseRequestService.setRefuseRequest(true);
                    } else if ("up".equals(pathVar)) {
                        refuseRequestService.setRefuseRequest(false);
                    }
                    return ServerResponse.ok().body(Mono.just("ok"), String.class);
                } catch (Throwable e) {
                    LOGGER.error("{} request err!", pathVar, e);
                    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                }
            });

    HttpHandler handler = RouterFunctions.toHttpHandler(manageRouterFunction);
    int managePort = serverPort - 1000;

    ReactorHttpHandlerAdapter inboundAdapter = new ReactorHttpHandlerAdapter(handler);

    // manage port
    HttpServer.create().port(managePort).handle(inboundAdapter).bind();
    // HttpServer.create(managePort).newHandler(inboundAdapter).block();

    LOGGER.info("management services run on port:{}", managePort);
}
 
Example #29
Source File: WebFluxServerDsl.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
/**
 * Configure routes via {@link RouterFunctions.Builder}.
 * @see org.springframework.fu.jafu.BeanDefinitionDsl#bean(Class, BeanDefinitionCustomizer...)
 */
public WebFluxServerDsl router(Consumer<RouterFunctions.Builder> routerDsl) {
	RouterFunctions.Builder builder = RouterFunctions.route();
	context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () -> {
		routerDsl.accept(builder);
		return builder.build();
	});
	return this;
}
 
Example #30
Source File: GatewaySampleApplication.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> testFunRouterFunction() {
	RouterFunction<ServerResponse> route = RouterFunctions.route(
			RequestPredicates.path("/testfun"),
			request -> ServerResponse.ok().body(BodyInserters.fromValue("hello")));
	return route;
}