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
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐