Spring Cloud Gateway 与 Eureka整合

Spring Cloud Gateway 与 Eureka整合

环境准备

  • Eureka Server端
  • Eureka Client端

配置Eureka并实现zuul的stripPrefix的效果

  • pom.xml添加如下配置,并在Application类中添加一些注解
    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    
@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}

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/(?.*)");
        config.setReplacement("/${segment}");
        GatewayFilter filter = new RewritePathGatewayFilterFactory()
                .apply(config);
        Function 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

你可能感兴趣的:(Spring Cloud Gateway 与 Eureka整合)