从零开始玩转SpringCloud(二):Gateway网关对接注册中心

简介:Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。

项目搭建

  1. 引入依赖
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <!--Eureka 客户端-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!--Gateway 路由-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

注意:不要引入spring-boot-starter-web包,会导致Gateway启动抛出异常,错误如下。因为Spring Cloud Gateway 是使用 netty+webflux实现,webflux与web是冲突的。

1
Consider defining a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' in your configuration.

  1. 在Application中使用@EnableEurekaClient

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package com.example.gateway;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

    @EnableEurekaClient
    @SpringBootApplication
    public class GatewayApplication {
    public static void main(String[] args) {
    SpringApplication.run(GatewayApplication.class, args);
    }
    }
  2. 配置自动将注册中心的服务映射为路由

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    server:
    port: 8081

    spring:
    application:
    name: gateway
    cloud:
    gateway:
    # 此处配置表示开启自动映射Eureka下发的路由
    discovery:
    locator:
    enabled: true
    lowerCaseServiceId: true

    eureka:
    client:
    # Eureka Server地址
    service-url:
    defaultZone: http://localhost:8760/eureka/
  3. 至此,已经可以直接通过gateway访问其他注册在Eureka中的服务的接口了。如客户端接口地址:http://localhost:8080/test,注册名称为client,则访问地址为http://localhost:8081/client/test。