gateway是springcloud中实现网关功能的常用组件,下面介绍gateway静态路由的两种配置方法
一 环境的搭建 1 添加核心依赖org.springframework.boot spring-boot-starter-webflux org.springframework.cloud spring-cloud-starter-gateway org.springframework.cloud spring-cloud-starter-netflix-eureka-client
由于网关也是属于微服务,所以要将该服务注册到注册中心,这里注册中心组件选择使用eureka
2 properties文件server.port=9527 spring.application.name=cloud-gateway myIp = localhost eureka.instance.hostname=cloud-gateway-service eureka.client.register-with-eureka=true eureka.client.fetch-registry=true eureka.client.service-url.defaultZone=http://localhost:7001/eureka3 主启动类
@SpringBootApplication
@EnableEurekaClient
public class CloudGatewayGateway9527Application {
public static void main(String[] args) {
SpringApplication.run(CloudGatewayGateway9527Application.class, args);
}
}
二 路由的配置
路由配置的方式有两种,但是要进行配置的内容一致,有:
- 路由规则的id,需要保持唯一性
- 断言,用于进行路由选择
- 经过断言判断后要进行访问的uri地址
下面是相关配置的演示
1 使用properties文件进行配置#以下为路由的配置
#路由的id,保持唯一即可
spring.cloud.gateway.routes[0].id=payment_route
#提供服务的路由地址
spring.cloud.gateway.routes[0].uri=http://${myIp}:8001
#断言,路径相匹配的进行路由
spring.cloud.gateway.routes[0].predicates[0]=Path=/payments/get/**
2 使用配置类进行配置
@Configuration
public class GateWayConfig {
@Bean
public RouteLocator routes1(RouteLocatorBuilder routeLocatorBuilder){
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
routes.route("path_route1",
r->r.path("/guonei").uri("http://news.baidu.com/guonei"));
return routes.build();
}
}



