第一首先是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 这个必须要有否则控制台没有错误,但是就是不能得到结果,我试了好久才知道的.