构建网关服务

1. 创建项目

使用Spring Initializer,选择Reactive GatewayEureka ClientSpring Boot ActuatorConfig Client,生成项目的pom.xml的核心文件内容如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<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>

2. 添加配置属性

/src/main/resources文件夹中创建application.yml文件:

spring:
    profiles:
        active: dev
    application:
        name: gateway-server    
    cloud:
        config:
            uri: http://192.168.10.110:8071/
            fail-fast: true
    config:
        import: 'optional:configserver:'

3. 集成Eureka

Spring Cloud Gateway可以与Netflix Eureka Discovery服务集成。要添加新的网关服务,第一步是在Spring配置服务器存储库中为此服务创建一个配置文件。对于这个示例,我们创建了gateway-server.yml文件。

接下来,我们将Eureka配置数据添加到刚刚创建的配置文件中:

server:
  port: 8072
eureka:
  instance:
    preferIpAddress: true
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://192.168.10.110:8070/eureka/

通过这样的配置,Spring Cloud Gateway将能够注册到Eureka服务注册中心,并发现其他服务的实例。

4. 配置 Actuator

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      enabled: true
      show-details: always
    gateway:
      enabled: true

只有配置了 management.endpoint.gateway.enabled=true 后,才能够访问 gateway 相关的 actuator 端口。

Last updated