SpringCloud 詳細網關gateway 與 eureka注冊中心 以及如何結合使用的案例講解


1. 什么是gateway,什么是eureka注冊中心以及為什么需要注冊

  首先博主經過一周的到處亂撞,各種奇葩案例,走過的坑就希望大伙不去踩坑。所以下面的案例就直擊重點,采用最簡單的案例來為大家講解,你一定會明白的!!!

  1.1什么是eureka Service注冊中心

    首先要明白為什么需要注冊,這里要用到SpringCloud的獨立模塊的概念,當我們一個大型項目有很多模塊時(例如 一個購物網站 有購物車模塊 用戶管理模塊 商品模塊等),如果需要某個模塊的接口去訪問資源時,

    我們就得知道它的具體ip +端口+接口 。這時如果有一個統一的管理購物網站的東西,我輸入

  • 統一管理地址+user----》訪問用戶模塊
  • 統一管理地址+cart-----》訪問購物車模塊

  這時有同學就會疑惑 我一個項目的ip不是同一個嗎,還需要一個統一管理地址不是多此一舉。如果你的項目的不同模塊處於不同服務器上,甚至所處區域都不一樣時,ip就會衍生出非常之多(大型公司 淘寶等為了減輕服務器壓力,在不同的地區放置了應對不同功能的服務器,整合成一個淘寶),這樣是不是就突出了統一管理地址的作用。

  而注冊中心就是把各個模塊統一注冊到eureka 注冊中心中,只需要用網關+模塊的應用名稱(可以理解為模塊的名字)就能訪問到該模塊的相關數據。

  1.2什么是gateway

    gateway通俗的簡單理解就是網絡協議轉換器,下面的案例中gateway暫時僅充當公司項目中的斷言-》轉發的目的。結合eureka注冊中心,gateway網關要想通過別名發現注冊到eureka中的服務,他自己也得注冊進去。下面上實例。

2. eureka Service模塊注冊流程

  2.1新建一個SpringBoot 項目(具體新建就不說了,我取名為eureka-demo)

 

 

主項目下只留pom,也就是上圖的文件布局,為什么只留pom 是因為后面的模塊才是各個具體功能模塊,而主項目的pom是為了給模塊的pom添加繼承,統一各個模塊的版本,方便管理。 

 

 eureka-demo的配置文件(pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>eureka-demo</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    
    
    <modules>
        <module>eureka-service</module>
        <module>eureka-server02</module>
        <module>server-provider</module>
        <module>server-consumer</module>
    </modules>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.6.RELEASE</version>
    </parent>


<!--    集中自定義版本-->
    <properties>
<!--        <maven.compiler.source>8</maven.compiler.source>-->
<!--        <maven.compiler.target>8</maven.compiler.target>-->
        <spring-cloud.version> Hoxton.SR1</spring-cloud.version>
    </properties>



    <dependencyManagement>
        <dependencies>
<!--            springCloud依賴-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type> pom</type>
                <scope>import</scope>
            </dependency>

            <!--增加eureka-server的依賴-->


        </dependencies>
    </dependencyManagement>

</project>

 

  2.2 新增模塊eureka-server 

  

 

  2.3 新建resources資源文件夾,編寫該模塊的pom文件

我這里時新建過了,所以是取消mark標記為資源文件,你們新建時就顯示標記就行。

  

 

pom文件如下(之后如果啟動模塊失敗就三處test 整個文件目錄)

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>eureka-service</artifactId>
  <version>1.0-SNAPSHOT</version>

  <parent>
    <groupId>org.example</groupId>
    <artifactId>eureka-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent> #====繼承父版本,達到版本統一。






  <dependencies>
<!--    測試依賴-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

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

    <!--    web依賴-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-netflix-eureka-server</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter</artifactId>
      </dependency>

  </dependencies>
</project>

 

   2.4 編寫application.yml文件(得在本模塊resources下新建)

  

server:
  port: 8761

spring:
  application:
    name: eureka-service

eureka:
  instance:
    hostname: eureka01

    prefer-ip-address: true #是否使用ip注冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} #ip:port

  client:
    register-with-eureka: true #是否將自己注冊到注冊中心
    fetch-registry: true #是否從注冊中心服務注冊信息
    service-url:          #注冊中心對外暴露的注冊地址
      defaultZone: http://localhost:8761/eureka/
#      http://${eureka.instance.hostname}:${server.port}/eureka/

 

 刪除新建本模塊下的App啟動類(就是想改個名字方便啟動時辨認)

 

 

 

 

 

 

package org.example;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@EnableEurekaServer
@SpringBootApplication
@RestController
public class EurekaServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServiceApplication.class);
    }

    @GetMapping("/user")
    public String getUser(){
        return "gateway ok";
    }---------后續為了gateway來測試它,本來是要寫在controller中的,這里只是為了方便測試。
}

  這里面寫了一個簡單的測試接口,方便gateway 攔截,並用網關+Application-name屬性去訪問該模塊。暫時寫道這里只需要啟動該模塊,訪問http://localhost:8761 進入如下界面說明注冊成功!!!

 

看到這里,總結以下:所謂的eureka注冊就是通過配置yml 和pom依賴並通過eureka可視化平台看到自己的注冊模塊,沒有難度吧。下面配置gateway

3. 配置gateway項目文件

  3.1新建項目。

  常規的新建Springboot文件,pom依賴下面有,所以不勾選依賴看下面的pom注釋也能明白有哪些依賴。

  3.2 pom編寫

  

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>gateway-study</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gateway-study</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    </properties>

    <dependencies>
        <!--引入gateway依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--gateway也是需要注冊到服務中心的-->
        <!--注入eureka client 依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.gatewaystudy.GatewayStudyApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

  3.3 yml配置以及講解

  

server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由"

routes:
- id: eureka-service #payment_routh #路由的ID,沒有固定規則,但要求唯一,建議配合服務名
#uri: http://localhost:8761 #匹配后提供服務的路由地址 沒有進行負載均衡
uri: lb://eureka-service #匹配后提供服務的路由地址-------這里用的動態路由格式統一為 lb://注冊進eureka服務中心的名字
predicates:
- Path=/server01/** #斷言,路徑相匹配的進行路由--------斷言也就是匹配方式,當識別到/servero1/**時就會跳轉上面的uri
filters: #這個必須寫
- StripPrefix=1 # 請求/name/bar/foo,去除掉前面兩個前綴之后,最后轉發到目標服務的路徑為/foo-----這里寫的是只去掉一個,多了自然會導致路徑錯誤,不同的訪問url配置也不同

eureka:
instance:
hostname: cloud-gateway-service
client: # 服務提供者provider注冊金eureka服務列表內
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://localhost:8761/eureka/

gateway啟動類如下

package com.example.gatewaystudy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.result.view.Rendering;

@EnableEurekaClient
@SpringBootApplication
public class GatewayStudyApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayStudyApplication.class, args);
    }

}

 

  

前面說過,gateway想要通過Application-name發現注冊到eureka的服務模塊,自己就也得注冊進去,多的部分也就是gateway配置部分。(總結就是匹配server01 然后轉發到上面的uri)

  3.4 啟動gateway,進行跨項目訪問

    輸入 localhost:9527/server01/user 得到下面的結果就全部完成了

 

需要注意一點:gateway項目引入的依賴是:

spring-cloud-starter-netflix-eureka-client

而模塊服務引入的依賴是
spring-cloud-netflix-eureka-server

 

總結上面的例子,我只舉例了一個服務中心的注冊。因為對於簡單的理解gateway+eureka足夠了,而使用yml的配置方式也是公司常用的使用方式。希望能幫助大家入門。少走彎路!!!!

 

 

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM