Gateway 网关使用入门

1.代码

cloud-gateway9527工程:

pom-这个工程也要注册进eureka所以也添加了eureka:

    <dependencies>
        <!-- gateway网关 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

#这里遇到了很多问题,有的说排除web依赖,但是对我还是没用。后来把别的依赖都排除了就可以了。不太清楚是哪个依赖冲突了,但是gateway也用不上那些,就都删了吧。

yml:

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: host_route
          uri: http://localhost:8001
          predicates:
            - Path=/payment/get/*
        - id: host_route
          uri: http://localhost:8001
          predicates:
            - Path=/payment/discovery

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/     #单机版
  instance:
    instance-id: gatewayservice
    prefer-ip-address: true

主程序:

@SpringBootApplication
@EnableEurekaClient
public class GatewayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GatewayMain9527.class, args);
    }
}

 

2.测试:

一开始访问payment8001是这样的:

 

 添加网关后也成功了:

 ************************************************************************分割线 ************************************************************************

文档:https://spring.io/projects/spring-cloud-gateway

以上是yml版本的,也可以使用java版本的:

需要一个配置类:

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route3",r->r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
        return routes.build();
    }

    @Bean
    public RouteLocator customRouteLocator2(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route4",r->r.path("/dayanjing").uri("https://home.cnblogs.com/u/dayanjing/")).build();
        return routes.build();
    }
}

#这里不明白为什么写payment8001的地址就不行,也没解决。。。

测试结果:

 

posted @ 2021-05-27 16:36  圣金巫灵  阅读(276)  评论(0编辑  收藏  举报