第一首先是pom文件
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
要添加上面的依賴
然後有兩站實現方式,一種是通過yml配置實現,一種是通過配置類實現,
1配置類實現
import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GatewayRoutes { @Bean public RouteLocator routeLocator(RouteLocatorBuilder builder) { return builder.routes() .route(r -> r.path("/hello/**") .filters( f -> f.stripPrefix(1)) .uri("lb://hello") ) .build(); }
這裏的paht: hello/** hello參數 ** 所有的方法 uri lb 負載均衡 lb://hello 是註冊在eureka的服務的名字
eureka: client: registerWithEureka: true fetchRegistry: true service-url: defaultZone: http://localhost:9601/eureka/ server: port: 9801
配置文件如上面的就可以了.瀏覽器打開http://localhost:9801/hello/get1 就可以看到相應的結果.
下面說通過配置實現:
配置文件如下:
eureka: client: registerWithEureka: true fetchRegistry: true service-url: defaultZone: http://localhost:9601/eureka/,http://localhost:9602/eureka/ server: port: 9801 spring: cloud: gateway: routes: - id: host1 uri: http://localhost:9606 predicates: - Path=/hello/** filters: - StripPrefix=1
其中的 filters: - StripPrefix=1 這個必須要有否則控制檯沒有錯誤,但是就是不能得到結果,我試了好久才知道的.