org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder Java Examples

The following examples show how to use org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder. 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: GateWayConfig.java    From codeway_service with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 自定义拦截规则
 *     id:固定,不同 id 对应不同的功能,可参考 官方文档
 *     uri:目标服务地址
 *     predicates:路由条件
 *     filters:过滤规则
 *     stripPrefix(0):剥夺前缀数字为几则删除路径上的几位,stripPrefix(2) /name/bar/foo -》 http://nameservice/foo.
 *     lb = load-balanced(负载均衡)
 * @param builder
 * @return RouteLocator
 */
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			// 用户服务
			.route("user_route", r -> r.path("/su/**").filters(f -> f.stripPrefix(1)).uri("lb://SERVICE-USER"))
			// 基础服务
			.route("base_route", r -> r.path("/ba/**").filters(f -> f.stripPrefix(1)).uri("lb://SERVICE-BASE"))
			// 文章服务
			.route("article_route", a -> a.path("/ar/**").filters(f -> f.stripPrefix(1)).uri("lb://SERVICE-ARTICLE"))

			// 授权、鉴权、第三方登录
			.route("auth_route", a -> a.path("/oauth/**").filters(f -> f.stripPrefix(0)).uri("lb://AUTHENTICATION-SERVER"))
			.route("social_route", a -> a.path("/social/**").filters(f -> f.stripPrefix(1)).uri("lb://AUTHENTICATION-SERVER"))

			// API
			.route("api_base_route", r -> r.path("/api/ba/**").filters(f -> f.stripPrefix(0)).uri("lb://SERVICE-BASE"))
			.route("api_article_route", a -> a.path("/api/ar/**").filters(f -> f.stripPrefix(0)).uri("lb://SERVICE-ARTICLE"))
			.route("api_user_route", a -> a.path("/api/su/**").filters(f -> f.stripPrefix(0)).uri("lb://SERVICE-USER"))

			.build();
}
 
Example #2
Source File: ReservationClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 6 votes vote down vote up
@Bean
RouteLocator gateway(RouteLocatorBuilder rlb) {
	return
		rlb
			.routes()
			.route(
				rSpec -> rSpec
					.host("*.foo.com").and().path("/proxy")
					.filters(
						spec -> spec
							.addResponseHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
							.setPath("/reservations")
							.requestRateLimiter(config -> config.setRateLimiter(redisRateLimiter()))
					)
					.uri("lb://reservation-service")
			)
			.build();
}
 
Example #3
Source File: RouteConfiguration.java    From microservice-integration with MIT License 6 votes vote down vote up
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route(r -> r.host("**.changeuri.org").and().header("X-Next-Url")
                    .filters(f -> f.requestHeaderToRequestUri("X-Next-Url"))
                    .uri("http://blueskykong.com"))
            .route(r -> r.host("**.changeuri.org").and().query("url")
                    .filters(f -> f.changeRequestUri(e -> Optional.of(URI.create(
                            e.getRequest().getQueryParams().getFirst("url")))))
                    .uri("http://blueskykong.com"))
            .build();
}
 
Example #4
Source File: ReservationClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 6 votes vote down vote up
@Bean
RouteLocator gateway(RouteLocatorBuilder rlb) {
	return rlb
		.routes()
		.route(
			routeSpec -> routeSpec
				.host("*.spring.com").and().path("/proxy")
				.filters(fSpec ->
					fSpec
						.setPath("/reservations")
						.addResponseHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
						.requestRateLimiter(rl -> rl
							.setRateLimiter(rl())
						)
				)
				.uri("http://localhost:8080")
		)
		.build();
}
 
Example #5
Source File: ModifyRequestBodyGatewayFilterFactorySslTimeoutTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
@DependsOn("testModifyRequestBodyGatewayFilterFactory")
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("test_modify_request_body_ssl_timeout",
			r -> r.order(-1).host("**.modifyrequestbodyssltimeout.org")
					.filters(f -> f.modifyRequestBody(String.class, String.class,
							MediaType.APPLICATION_JSON_VALUE,
							(serverWebExchange, aVoid) -> {
								byte[] largeBody = new byte[10 * 1024 * 1024];
								return Mono.just(new String(largeBody));
							}))
					.uri(uri))
			.route("test_modify_request_body_exception", r -> r.order(-1)
					.host("**.modifyrequestbodyexception.org")
					.filters(f -> f.modifyRequestBody(String.class, String.class,
							MediaType.APPLICATION_JSON_VALUE,
							(serverWebExchange, body) -> {
								return Mono.error(
										new Exception("modify body exception"));
							}))
					.uri(uri))
			.build();
}
 
Example #6
Source File: RetryGatewayFilterFactoryIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
public RouteLocator hystrixRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			.route("retry_java", r -> r.host("**.retryjava.org")
					.filters(f -> f.prefixPath("/httpbin")
							.retry(config -> config.setRetries(2)
									.setMethods(HttpMethod.POST, HttpMethod.GET)))
					.uri(uri))
			.route("retry_only_get", r -> r.host("**.retry-only-get.org")
					.filters(f -> f.prefixPath("/httpbin")
							.retry(config -> config.setRetries(2)
									.setMethods(HttpMethod.GET)))
					.uri(uri))
			.route("retry_with_backoff", r -> r.host("**.retrywithbackoff.org")
					.filters(f -> f.prefixPath("/httpbin").retry(config -> {
						config.setRetries(2).setBackoff(Duration.ofMillis(100),
								null, 2, true);
					})).uri(uri))

			.route("retry_with_loadbalancer",
					r -> r.host("**.retrywithloadbalancer.org")
							.filters(f -> f.prefixPath("/httpbin")
									.retry(config -> config.setRetries(2)))
							.uri("lb://badservice2"))
			.build();
}
 
Example #7
Source File: TweetClientApplication.java    From reactive-spring-online-training with Apache License 2.0 6 votes vote down vote up
@Bean
RouteLocator gateway(RouteLocatorBuilder rlb) {
		return rlb
			.routes()
			.route(rSpec ->
				rSpec
					.path("/proxy").and().host("*.foo.gw")
					.filters(fSpec -> fSpec.requestRateLimiter(config ->
						config
							.setRateLimiter(this.redisRateLimiter())
							.setKeyResolver(new PrincipalNameKeyResolver())
					))
					.uri("http://localhost:8080/hashtags")
			)
			.build();

}
 
Example #8
Source File: ModifyResponseBodyGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("modify_response_java_test",
			r -> r.path("/").and().host("www.modifyresponsebodyjava.org")
					.filters(f -> f.prefixPath("/httpbin").modifyResponseBody(
							String.class, Map.class,
							(webExchange, originalResponse) -> {
								Map<String, Object> modifiedResponse = new HashMap<>();
								modifiedResponse.put("value", originalResponse);
								modifiedResponse.put("length",
										originalResponse.length());
								return Mono.just(modifiedResponse);
							}))
					.uri(uri))
			.route("modify_response_java_test_to_large", r -> r.path("/").and()
					.host("www.modifyresponsebodyjavatoolarge.org")
					.filters(f -> f.prefixPath("/httpbin").modifyResponseBody(
							String.class, String.class,
							(webExchange, originalResponse) -> {
								return Mono.just(toLarge);
							}))
					.uri(uri))
			.build();
}
 
Example #9
Source File: RedisRateLimiterConfigTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("custom_redis_rate_limiter",
			r -> r.path("/custom").filters(f -> f.requestRateLimiter()
					.rateLimiter(RedisRateLimiter.class,
							rl -> rl.setBurstCapacity(40).setReplenishRate(20)
									.setRequestedTokens(10))
					.and()).uri("http://localhost"))
			.route("alt_custom_redis_rate_limiter",
					r -> r.path("/custom")
							.filters(f -> f.requestRateLimiter(
									c -> c.setRateLimiter(myRateLimiter())))
							.uri("http://localhost"))
			.build();

}
 
Example #10
Source File: JeecgGatewayApplication.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("path_route", r -> r.path("/get")
                    .uri("http://httpbin.org"))
            .route("baidu_path_route", r -> r.path("/baidu")
                    .uri("https://news.baidu.com/guonei"))
            .route("host_route", r -> r.host("*.myhost.org")
                    .uri("http://httpbin.org"))
            .route("rewrite_route", r -> r.host("*.rewrite.org")
                    .filters(f -> f.rewritePath("/foo/(?<segment>.*)", "/${segment}"))
                    .uri("http://httpbin.org"))
            .route("hystrix_route", r -> r.host("*.hystrix.org")
                    .filters(f -> f.hystrix(c -> c.setName("slowcmd")))
                    .uri("http://httpbin.org"))
            .route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
                    .filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
                    .uri("http://httpbin.org"))
            .build();
}
 
Example #11
Source File: GateWayConfig.java    From codeway_service with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 自定义拦截规则
 *     id:固定,不同 id 对应不同的功能,可参考 官方文档
 *     uri:目标服务地址
 *     predicates:路由条件
 *     filters:过滤规则
 *     stripPrefix(0):剥夺前缀数字为几则删除路径上的几位,stripPrefix(2) /name/bar/foo -》 http://nameservice/foo.
 *     lb = load-balanced(负载均衡)
 * @param builder
 * @return RouteLocator
 */
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			// 用户服务
			.route("user_route", r -> r.path("/su/**").filters(f -> f.stripPrefix(1)).uri("lb://SERVICE-USER"))
			// 基础服务
			.route("base_route", r -> r.path("/ba/**").filters(f -> f.stripPrefix(1)).uri("lb://SERVICE-BASE"))
			// 文章服务
			.route("article_route", a -> a.path("/ar/**").filters(f -> f.stripPrefix(1)).uri("lb://SERVICE-ARTICLE"))

			// 授权、鉴权、第三方登录
			.route("auth_route", a -> a.path("/oauth/**").filters(f -> f.stripPrefix(0)).uri("lb://AUTHENTICATION-SERVER"))
			.route("social_route", a -> a.path("/social/**").filters(f -> f.stripPrefix(1)).uri("lb://AUTHENTICATION-SERVER"))

			// API
			.route("api_base_route", r -> r.path("/api/ba/**").filters(f -> f.stripPrefix(0)).uri("lb://SERVICE-BASE"))
			.route("api_article_route", a -> a.path("/api/ar/**").filters(f -> f.stripPrefix(0)).uri("lb://SERVICE-ARTICLE"))
			.route("api_user_route", a -> a.path("/api/su/**").filters(f -> f.stripPrefix(0)).uri("lb://SERVICE-USER"))

			.build();
}
 
Example #12
Source File: NonStandardHeadersInResponseTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			.route("non_standard_header_route", r -> r.path("/get-image/**")
					.filters(f -> f.addRequestHeader(HttpHeaders.HOST,
							"www.addrequestparameter.org").stripPrefix(1))
					.uri("http://localhost:" + port + "/get"))
			.route("internal_route", r -> r.path("/get/**")
					.filters(f -> f.prefixPath("/httpbin")).uri(uri))
			.build();
}
 
Example #13
Source File: NettyRoutingFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
	return builder.routes()
			.route(p -> p.path("/mockexample")
					.filters(f -> f.prefixPath("/httpbin"))
					.uri("http://example.com"))
			.build();
}
 
Example #14
Source File: AddRequestHeaderGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("add_request_header_java_test",
			r -> r.path("/headers").and().host("{sub}.addrequestheaderjava.org")
					.filters(f -> f.prefixPath("/httpbin")
							.addRequestHeader("X-Request-Acme", "ValueB-{sub}"))
					.uri(uri))
			.build();
}
 
Example #15
Source File: ModifyBodyRouteConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
      .route("modify_request_body", r -> r.path("/post")
        .filters(f -> f.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
          (exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri("https://httpbin.org"))
      .build();
}
 
Example #16
Source File: PrincipalNameKeyResolverIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route(r -> r.path("/myapi/**")
			.filters(f -> f
					.requestRateLimiter(c -> c.setRateLimiter(myRateLimiter()))
					.prefixPath("/downstream"))
			.uri("http://localhost:" + port)).build();
}
 
Example #17
Source File: CustomPredicatesConfig.java    From tutorials with MIT License 5 votes vote down vote up
public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) {

        return builder.routes()
          .route("dsl_golden_route", r -> r.path("/dsl_api/**")
            .filters(f -> f.stripPrefix(1))
            .uri("https://httpbin.org")
            .predicate(gf.apply(new Config(true, "customerId"))))
          .route("dsl_common_route", r -> r.path("/dsl_api/**")
            .filters(f -> f.stripPrefix(1))
            .uri("https://httpbin.org")
            .predicate(gf.apply(new Config(false, "customerId"))))             
          .build();
    }
 
Example #18
Source File: AddRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("add_request_param_java_test",
			r -> r.path("/get").and().host("{sub}.addreqparamjava.org")
					.filters(f -> f.prefixPath("/httpbin")
							.addRequestParameter("example", "ValueB-{sub}"))
					.uri(uri))
			.build();
}
 
Example #19
Source File: ServiceRouteConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RouteLocator routes(RouteLocatorBuilder builder, LoggingGatewayFilterFactory loggingFactory) {

    return builder.routes()
        .route("service_route_java_config", r -> r.path("/service/**")
            .filters(f -> f.rewritePath("/service(?<segment>/?.*)", "$\\{segment}")
                .filter(loggingFactory.apply(new Config("My Custom Message", true, true))))
            .uri("http://localhost:8081"))
        .build();
}
 
Example #20
Source File: RemoteAddrRoutePredicateFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("x_forwarded_for_test", r -> r
			.path("/xforwardfor").and()
			.remoteAddr(XForwardedRemoteAddressResolver.maxTrustedIndex(1),
					"12.34.56.78")
			.filters(f -> f.setStatus(200)).uri(uri)).build();
}
 
Example #21
Source File: SetResponseHeaderGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("test_set_response_header_dsl",
			r -> r.order(-1).host("{sub}.setresponseheaderdsl.org")
					.filters(f -> f.prefixPath("/httpbin")
							.addResponseHeader("X-Res-Foo", "First")
							.setResponseHeader("X-Res-Foo", "Second-{sub}"))
					.uri(uri))
			.build();
}
 
Example #22
Source File: PreserveHostHeaderGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("test_preserve_host_header",
			r -> r.order(-1).host("**.preservehostheader.org")
					.filters(f -> f.prefixPath("/httpbin").preserveHostHeader()
							.setRequestHeader("Host", "myhost.net"))
					.uri(uri))
			.build();
}
 
Example #23
Source File: ModifyRequestBodyGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("test_modify_request_body",
			r -> r.order(-1).host("**.modifyrequestbody.org")
					.filters(f -> f.modifyRequestBody(String.class, String.class,
							MediaType.APPLICATION_JSON_VALUE,
							(serverWebExchange, aVoid) -> {
								return Mono.just("modifyrequest");
							}))
					.uri(uri))
			.route("test_modify_request_body_empty", r -> r.order(-1)
					.host("**.modifyrequestbodyempty.org")
					.filters(f -> f.modifyRequestBody(String.class, String.class,
							MediaType.APPLICATION_JSON_VALUE,
							(serverWebExchange, body) -> {
								if (body == null) {
									return Mono.just("modifyrequest");
								}
								return Mono.just(body.toUpperCase());
							}))
					.uri(uri))
			.route("test_modify_request_body_to_large", r -> r.order(-1)
					.host("**.modifyrequestbodyemptytolarge.org")
					.filters(f -> f.modifyRequestBody(String.class, String.class,
							MediaType.APPLICATION_JSON_VALUE,
							(serverWebExchange, body) -> {
								return Mono.just(
										"tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge-tolarge");
							}))
					.uri(uri))
			.build();
}
 
Example #24
Source File: ModifyResponseBodyGatewayFilterFactoryGzipTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("modify_response_java_test_gzip",
			r -> r.path("/gzip").and().host("www.modifyresponsebodyjava.org")
					.filters(f -> f.modifyResponseBody(String.class, Map.class,
							(webExchange, originalResponse) -> {
								Map<String, Object> modifiedResponse = new HashMap<>();
								modifiedResponse.put("value", originalResponse);
								modifiedResponse.put("length",
										originalResponse.length());
								return Mono.just(modifiedResponse);
							}))
					.uri(uri))
			.build();
}
 
Example #25
Source File: RemoveRequestParameterGatewayFilterFactoryIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes().route("removerequestparam_java_test", r -> r
			.path("/get").and().host("**.removerequestparamjava.org")
			.filters(f -> f.prefixPath("/httpbin").removeRequestParameter("foo"))
			.uri(uri)).build();
}
 
Example #26
Source File: SetStatusGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator myRouteLocator(RouteLocatorBuilder builder) {
	// @formatter:off
	return builder.routes()
			.route("test_custom_http_status",
					r -> r.host("*.setcustomstatus.org")
							.filters(f -> f.setStatus(432))
							.uri(uri))
			.build();
	// @formatter:on
}
 
Example #27
Source File: SetStatusGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator enumRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			.route("test_enum_http_status", r -> r.host("*.setenumstatus.org")
					.filters(f -> f.setStatus(HttpStatus.UNAUTHORIZED)).uri(uri))
			.build();
}
 
Example #28
Source File: GatewayMetricsFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator myRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			.route("test_custom_http_status_metrics",
					r -> r.host("*.setcustomstatusmetrics.org")
							.filters(f -> f.setStatus(432)).uri(testUri))
			.build();
}
 
Example #29
Source File: SseIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator sseRouteLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			.route("sse_route",
					r -> r.alwaysTrue().uri("http://localhost:" + this.port))
			.build();
}
 
Example #30
Source File: ReadBodyPredicateFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
	return builder.routes()
			.route(p -> p.path("/events").and().method(HttpMethod.POST).and()
					.readBody(Event.class, eventPredicate("message.channels"))
					.filters(f -> f.setPath("/messageChannel/events"))
					.uri("lb://messageChannel"))
			.route(p -> p.path("/events").and().method(HttpMethod.POST).and()
					.readBody(Event.class, eventPredicate("message"))
					.filters(f -> f.setPath("/message/events"))
					.uri("lb://message"))
			.build();
}