入门配置
程序员文章站
2022-03-14 10:17:00
...
入门配置
1、cloud-gateway-gateway9527
2、POM
<dependencies>
<!--新增gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、YML
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes:
- id: payment_routh #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** #断言,路径相匹配的进行路由
- id: payment_routh2
uri: http://localhost:8001
predicates:
- Path=/payment/lb/** #断言,路径相匹配的进行路由
eureka:
instance:
hostname: cloud-gateway-service
client:
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eure
4、主启动类
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
public static void main(String[] args) {
SpringApplication.run( GateWayMain9527.class,args);
}
}
测试
希望看到的效果:我们目前不想暴露8001端口,希望在8001外面套一层9527。
1、启动7001
2、启动cloud-provider-payment8001
3、启动9527网关
4、添加网关前:访问http://localhost:8001/payment/get/31可以拿到结果
5、添加网关后:访问http://localhost:9527/payment/get/31也可以拿到结果。
Gateway网关路由有两种配置方式
1、yml:上面的方式就是yml
2、代码中注入RouteLocator的Bean
需求:访问http://localhost:9527/guonei就跳转到http://news.baidu.com/guonei(即通过9527网关访问到外网的百度新闻网址)
@Configuration
public class GateWayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
// 相当于访问http://localhost:9527/guonei就是访问http://news.baidu.com/guonei
routes.route("path_rote_sl",
r -> r.path("/guonei").
uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
}