從零開始玩轉SpringCloud(二):Gateway網關對接註冊中心

從零開始玩轉SpringCloud(二):Gateway網關對接註冊中心

簡介:Spring Cloud Gateway旨在爲微服務架構提供一種簡單而有效的統一的API路由管理方式。

項目搭建

  1. 引入依賴
<!--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是衝突的。

Consider defining a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' in your configuration.
  1. 在Application中使用@EnableEurekaClient
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);
    }
}

  1. 配置自動將註冊中心的服務映射爲路由
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/
  1. 至此,已經可以直接通過gateway訪問其他註冊在Eureka中的服務的接口了。如客戶端接口地址:http://localhost:8080/test,註冊名稱爲client,則訪問地址爲http://localhost:8081/client/test。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章