Spring Cloud 第二代网关 Gateway

2023-01-04  本文已影响0人  Tinyspot

1. Gateway

1.1 路由(Route)

1.2 断言(Predicate)

1.3 过滤器(Filter)

2. 实战

<dependencies>
    <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>
</dependencies>

2.1 路由配置(服务IP)

server:
  port: 8010

spring:
  application:
    name: concrete-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 开启注册与发现功能
          lower-case-service-id: true # 把服务名转换为小写,Eureka中默认是大写
      routes:
      - id: eureka-client
        uri: http://127.0.0.1:8770
        predicates:
        - path=/user/**
@SpringBootApplication
public class ConcreteGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConcreteGatewayApplication.class, args);
    }
}

请求地址 http://localhost:8010/user/query

2.2 动态路由配置(面向服务的路由)

@SpringBootApplication
@EnableEurekaClient
public class ConcreteGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConcreteGatewayApplication.class, args);
    }
}
server:
  port: 8010

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

spring:
  application:
    name: concrete-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 开启注册与发现功能
          lower-case-service-id: true # 把服务名转换为小写,Eureka中默认是大写
      routes: # List 类型写法:横线 或 逗号 标识一个对象
      - id: eureka-client # 自定义标识,唯一
        uri: lb://concrete-eureka-client # lb表示从注册中心获取服务
        # predicates: Path=/user/**
        predicates:
        - Path=/user/**

Path=/user/** 表示多级 Path, 例如 /user/query/1001

上一篇下一篇

猜你喜欢

热点阅读