Spring Cloud Gateway 与 Eureka整合
Spring Cloud Gateway 与 Eureka整合环境准备Eureka Server端Eureka Client端核心代码在pom.xml添加如下配置,并在Application类中添加一些注解<dependency><gro
·
Spring Cloud Gateway 与 Eureka整合
环境准备
- Eureka Server端
- Eureka Client端
配置Eureka并实现zuul的stripPrefix的效果
- 在
pom.xml
添加如下配置,并在Application类中添加一些注解
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
@EnableEurekaClient
@EnableDiscoveryClient
- application.yml配置(实现方式1)
server:
port: 8080
spring:
application:
name: spring-cloud-gateway
cloud:
gateway:
routes:
- id: ribbon_test
uri: lb://service-ribbon
predicates:
- Path=/api-a/**
#实现方式1
filters:
- RewritePath=/api-a/(?<segment>.*), /$\{segment}
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8761/eureka/
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
- 在SpringCloudGatewayApplication.java中添加如下代码。(实现方式2)
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
//实现方式2
//配置过滤规则
RewritePathGatewayFilterFactory.Config config = new RewritePathGatewayFilterFactory.Config();
config.setRegexp("/api-b/(?<segment>.*)");
config.setReplacement("/${segment}");
GatewayFilter filter = new RewritePathGatewayFilterFactory()
.apply(config);
Function<GatewayFilterSpec, UriSpec> fn = gatewayFilterSpec -> gatewayFilterSpec.filter(filter);
return builder.routes()
//basic proxy
.route(r -> r.path("/api-b/**")
//导入配置
.filters(fn)
.uri("lb://service-feign")
).build();
}
效果
- 请求
http://localhost:8080/api-a/learn?name=test
,访问的是http://service-ribbon/learn?name=test
- 请求
http://localhost:8080/api-b/learn?name=test
,访问的是http://service-feign/learn?name=test
更多推荐
已为社区贡献1条内容
所有评论(0)