我在 application.yml 中设置了上下文路径
server:
port: 4177
max-http-header-size: 65536
tomcat.accesslog:
enabled: true
servlet:
context-path: /gb-integration
Run Code Online (Sandbox Code Playgroud)
我已经配置了一些路由
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
final String sbl = "http://localhost:4178";
return builder.routes()
//gb-sbl-rest
.route("sbl", r -> r
.path("/sbl/**")
.filters(f -> f.rewritePath("/sbl/(?<segment>.*)", "/gb-sbl/${segment}"))
.uri(sbl)).build();
}
Run Code Online (Sandbox Code Playgroud)
我希望使用 localhost:4177/gb-integration/sbl/** 访问 API 网关,但是它仅在 localhost:4177/sbl/** 上工作
看来我的上下文路径被忽略了。有什么想法可以让我的上下文路径在我的所有路线上工作吗?
我将 Spring Cloud Gateway Greenwich.SR1 与 Spring Boot 2.1.5 结合使用。我正在尝试为我的下游服务创建一个网关。网关的部分工作是为下游请求提供全局错误页面。当下游服务返回 HTTP 403 响应时,我希望网关提供合适的错误页面。
我目前正在使用这样的自定义过滤器
public class ForbiddenFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Override
public String name() {
return "Forbidden";
}
@Override
public GatewayFilter apply(Object o) {
return (exchange, chain) -> chain.filter(exchange).then(
Mono.defer(() -> {
if (!exchange.getResponse().isCommitted() &&
HttpStatus.FORBIDDEN.equals(exchange.getResponse().getStatusCode())) {
return Mono.error(new ResponseStatusException(HttpStatus.FORBIDDEN));
}
return Mono.empty();
}));
}
}
Run Code Online (Sandbox Code Playgroud)
我还设置了一个403.html文件src/main/resources/templates/error/。
问题在于网关返回的 403 响应的正文为空,而不是 html 文件的内容。在调试过程中,我可以看到DefaultErrorWebExceptionHandler以 a 的形式创建了正确的主体Mono<ServerResponse>,但它从未写入实际响应。
有没有其他方法可以让它发挥作用?
我是 spring-cloud-gateway 的新手,如果我按预期方式解决了我的问题,我无法回答这个问题。我希望有人能给我指出正确的方向,提供建议或提供一些示例性示例代码。
要求:我的 spring-cloud-gateway 服务的传入请求应转发到正确的后端服务(有 X 个这样的后端服务,每个后端服务负责特定任务)。请求本身不包含足够的信息来决定路由到哪个后端服务。
存在附加的 REST 服务,可将任意 URL 映射到负责后端服务名称。响应格式是一些小的 JSON,包含要转发到的后端服务的名称。
使用 spring-cloud-gateway 实现此功能的最简单/最佳/最智能/预期的解决方案是什么?
我尝试实现一个GatewayFilter首先调用映射服务并取决于GATEWAY_REQUEST_URL_ATTR交换结果集的方法。这工作正常。但我还有其他问题。
.uri("not://needed"))路线设置中的部分 可以省略吗?
为什么订单金额需要高于9999?(参见代码示例)
@SpringBootApplication
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes().route(r -> r
.alwaysTrue()
.filters(f -> f.filter(new CustomRequestFilter()))
.uri("not://needed")) // how to omit ?
.build();
}
public static class CustomRequestFilter implements GatewayFilter, Ordered {
@Override
public int getOrder() {
return 10000; // …Run Code Online (Sandbox Code Playgroud) 我使用 Spring Cloud Gateway 作为边缘服务器。这就是流程
如果请求具有名为“x-foo”的标头,则查找标头值,从另一台服务器获取字符串并将该字符串作为响应发送,而不是实际代理请求。
这是 Filter DSL 的代码
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("foo-filter", r -> r.header('x-foo').and().header("x-intercepted").negate()
.filters(f -> f.filter(fooFilter))
.uri("http://localhost:8081")) // 8081 is self port, there are other proxy related configurations too
.build();
}
Run Code Online (Sandbox Code Playgroud)
Foo 过滤器的代码
@Component
@Slf4j
public class FooFilter implements GatewayFilter {
@Autowired
private ReactiveRedisOperations<String, String> redisOps;
@Value("${header-name}")
private String headerName;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
var foo = request.getHeaders().getFirst(headerName);
return redisOps.opsForHash()
.get("foo:" + foo, …Run Code Online (Sandbox Code Playgroud) 我是否仍然需要 NGINX 来提供 JS 等静态内容以及向后端反向代理请求,或者仅使用 Spring Cloud Gateway 即可完成?Spring 文档有以下图像:
我在那里没有找到有关如何将静态内容返回给客户端的描述,这是否意味着它被认为是不好的做法,并且我需要反向代理的额外步骤来增加其延迟?如果没有,我在哪里可以找到有关如何使用 Spring Cloud Gateway 执行此操作的更多信息,特别是如果我要使用 Spring Gateway 进行 oauth2 授权代码流身份验证?
运行 Spring Cloud Gateway 时出现以下错误。下面给出了对应的yml文件和我的依赖
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-04-04 18:28:56.698 ERROR 6944 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method tokenRelayGatewayFilterFactory in org.springframework.cloud.security.oauth2.gateway.TokenRelayAutoConfiguration required a bean of type 'org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'authorizedClientRepository' in 'ReactiveOAuth2ClientConfigurations.ReactiveOAuth2ClientConfiguration' not loaded because @ConditionalOnBean (types: org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; SearchStrategy: all) did not find …Run Code Online (Sandbox Code Playgroud) spring spring-security oauth-2.0 microservices spring-cloud-gateway
我们可以使用 Spring cloud gateway 作为转发代理吗?我绑了,不是吗,并且被 HTTPS 流量困住了。网关无法支持“HTTPS - CONNECT 请求”我知道底层使用了 Netty,但喜欢使用 Netty 的其他功能网关因此想将其用作转发代理
用例 在网关路由规则中有一些内部站点 URL,并且 URL 的其余部分必须是直通,就像转发代理的工作方式一样。我有一个示例通配符配置来测试转发代理设置,但 HTTPS 流量无法通过。
cloud:
gateway:
routes:
- id: wildcard_route
uri: no://op
predicates:
- Path=/**
Run Code Online (Sandbox Code Playgroud)
我需要一些有关如何在 Spring Cloud gateway 中启用转发代理的指导
我在 Spring Boot 2.3.4 中有以下工作代码
public Route.AsyncBuilder apply(PredicateSpec route) {
return route
.path("/api/external/**")
.filters(f -> f
.removeRequestHeader("Cookie")
.filter(loggingGatewayFilter)
.filter(oauth2GatewayFilter)
.filter(this::filter)
)
.uri("lb://external-url");
}
Run Code Online (Sandbox Code Playgroud)
配置:
external-url:
ribbon:
listOfServers: "http://external01.com,http://external02.com"
NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
Run Code Online (Sandbox Code Playgroud)
当我将 Spring Boot 版本升级到 2.4.2 时,代码必须更改为以下内容。
public Buildable<Route> apply(PredicateSpec route) {
return route
.path("/api/external/**")
.filters(f -> f
.removeRequestHeader("Cookie")
.filter(loggingGatewayFilter)
.filter(oauth2GatewayFilter)
.filter(this::filter)
)
.uri("lb://external-url");
}
Run Code Online (Sandbox Code Playgroud)
由于 netflix-ribbon 已在 Spring Boot 2.4.2 中删除,我必须添加这些依赖项。在路由中它给出以下警告。这意味着负载均衡器未初始化。
o.s.c.l.core.RoundRobinLoadBalancer : No servers available for service: external-url
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?我可以尝试将其迁移到弹簧负载平衡器中吗?
升级后的依赖树:
[INFO] +- org.apache.commons:commons-lang3:jar:3.9:compile
[INFO] +- com.internetitem:logback-elasticsearch-appender:jar:1.6:compile …Run Code Online (Sandbox Code Playgroud) spring-boot spring-cloud spring-cloud-netflix spring-cloud-gateway spring-cloud-loadbalancer
我有一个非常简单的测试:
@SpringBootTest(properties = {"instance.role=GATEWAY", "instance.name=test-instance", "debug=true"})
@TestPropertySource(locations = {"classpath:application.yaml"})
class GatewayWiringTest {
@Autowired
private MySpringBootApplication application;
@Test
void gatewayConfigLoads() {
assertThat(application).isNotNull();
}
}
Run Code Online (Sandbox Code Playgroud)
由于我的应用程序以不同的 bean 配置启动,根据分配的角色,我使用此类测试来测试每个配置是否可加载。
它确实在 Spring Boot 2.7 上运行没有问题。它不能与 Spring Boot 3.0 一起运行(显然,在将 Java 也更新到版本 17 后,而不仅仅是 spring/spring boot 依赖项)。错误的根本原因是:
org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。
我已将问题追溯到GatewayAutoConfiguration未评估加载的 Spring Cloud Gateway 服务器依赖项中的类 - 这是应该提供缺少的 bean 的自动配置类。
我还通过运行测试并查看类路径来验证执行测试时该类位于类路径上。mvn -X问题不在于加载类的两个条件之一评估为 false,问题在于这些条件从一开始就没有得到评估 - 使用生成的--debug条件评估报告运行测试,并且该类GatewayAutoConfiguration没有出现在两个列表中的任何一个中 - 匹配和不匹配的条件。
为什么不被处理?与 Spring Boot 2.7 相比,在这方面我需要对 Spring Boot …
我想在 Spring Cloud Gateway 中的每个请求的日志中显示traceId。然而,traceId和spanId只是空的。
日志配置如下:
logging:
pattern:
level: "%5p [TRACE_ID: %X{traceId:-}] [SPAN_ID: %X{spanId:-}]"Run Code Online (Sandbox Code Playgroud)
pom.xml 的一部分:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>3.0.1</version>
</dependency>Run Code Online (Sandbox Code Playgroud)
spring-boot ×4
spring ×3
spring-cloud ×3
micrometer ×1
nginx ×1
oauth ×1
oauth-2.0 ×1
spring-3 ×1