IDEA Spring cloud微服務項目搭建(配置中心config/注冊中心Eureka/網關路由zuul 網關路由getway)0基礎圖文教程


首先來說明本教程中使用二種網關(zuul與getway,選其中一種即可) 項目結構如下 ,最后會附上整個教程代碼提供下載


demo.parent
    springCloud.registry    808 注冊中心        http://localhost:808/
    springCloud.config      809 配置中心
    springCloud.zuul        800 路由網關(zuul)   直接訪問zuul網關 http://localhost:800/test/page2
    springCloud.geteway 801 路由網關(getway)     直接訪問geteway網關 http://localhost:801/test/page2
    demo.webUI              805 系統webUI        http://localhost:805/testUI/page2
                                                通過zuul: http://localhost:800/webui/testUI/page2
                                                通過geteway: http://localhost:801/webui/testUI/page2
    demo.webAPI             806 系統WebAPI       http://localhost:806/testAPI/page2
                                                通過zuul: http://localhost:800/webapi/testAPI/page2
                                                通過geteway: http://localhost:801/webapi/testAPI/page2
    ...........             可以添加更多的微服務

 先來一張整個項目架構截圖

 

 

 

 

 

一.創建父項目

1。點菜單file->new Project 選Maven ,直接點Next

 

2.輸入GroupId和artifactid,點Next

 

3.輸入項目名稱,和存放目錄點Finish

 

 

 4.新建完成后刪除src目錄和其他無關文件,只保留pom.xml與.iml文件,如下圖

 

 

6.修改父項目pom.xml文件:

說明:springboot2.4以上不支持zuul,這里用了spring boot2.3.6,后面所有項目都需要使用Module, 如果你用getway的話可以用最新版本(2.4及以上)

再次說明:Spring Boot版本與Spring Cloud版本有對應關系,否則你的項目會啟動不了,對應參考:https://spring.io/projects/spring-cloud

  

 修改pom.xml文件內容如下(注意修改springboot與spring cloud版本對應,注意把version改為1.0)

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0</version>
    <packaging>pom</packaging>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    </properties>

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

</project>

 

二.注冊中心 springCloud.registry (eureka)

1.右擊項目名稱-new->Module

 2.選“Spring Initializr" 點Next

  3.輸入Module名稱,注意把java版本改為1.8

  3.選中Spring Cloud Discovery-> 勾選Eureka Server (這是注冊服務發現的框架) ,Spring Boot注意改為2.3.6 點Next

 4.輸入Module name:

  4.給注冊中心的sringboot啟動類添加注解 @EnableEurekaServer

修改項目編碼格式 File->setting->editor 中全改為UTF-8,否則后面新建yml文件格式可能會有問題

  5.注冊中心 刪除resources/application.properties 新建application.yml 內容如下 

server:
  port: 808 #注冊中心端口
eureka:
  server:
    enable-self-preservation: false  # 設為false,關閉自我保護,會清理無效節點
    eviction-interval-timer-in-ms: 30000  # 清理無效節點間隔時間(單位毫秒,默認是60*1000)
  instance:
    hostname: 127.0.0.1
    preferIpAddress: true
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

6.修改注冊中心的的pom文件(修改parent結點為父項目,刪除properties結點,刪除dependencyManagement結點(因為父項目已經引用))內容如下:

<?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>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>1.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>registry</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>registry</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</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>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

注冊中心項目結構如下:

 

 7。啟動注冊中心是否成功

   啟動日志如下

 

在瀏覽器訪問:http://localhost:808/ 得到如下圖 表示注冊中心啟動成功

 

三.配置中心 springCloud.config  

1.前面過程與第二步一樣,在選模塊需要

勾選 Spring Cloud Cofnig 中的 Config Server

勾選 Spring Cloud Discovery 中的 Eureka Discovery Client 

記得Spring Boot版本為2.3.6

  2.給配置中心的spring boot啟動類添加二個注解如下圖

@EnableConfigServer

@EnableEurekaClient

  3. 刪除resources/application.properties 新建application.yml  內容如下 

spring:
  profiles:
    active: native
  application:
    name: springCloud.config

server:
  port: 809 #配置中心端口

eureka:
  client:
    serviceUrl:
      defaultZone: http://${host:localhost}:808/eureka/
    registry-fetch-interval-seconds: 5 # 拉取服務注冊信息間隔時間 (默認為30秒)
  instance:
    lease-expiration-duration-in-seconds: 60  # 注冊中心超過這個時間沒收到心跳,會視為無效節點(默認為90秒)
    lease-renewal-interval-in-seconds: 30  # 發送心跳間隔時間(默認30秒)
    preferIpAddress: true
    instanceId: ${spring.cloud.client.ip-address}:${server.port}

4.在resources目錄下添加application-native.yml文件,內容如下:

spring:
  cloud:
    config:
      server:
        native:
          searchLocations: classpath:/config/

5.配置中心目錄結構如下,添加config目錄,依次添加

  config-dev.yml  開發環境的配置文件

  config-prod.yml 生產環境的配置文件

  config-test.yml   測試環境的配置文件

  以下是config-dev.yml文件內容,其他幾個文件內容完全一樣,可根據要求修改參數即可

############開發環境配置文件###################

registry:
   url: http://${host:localhost}:808/eureka/  #注冊中心的地址與端口,方便給其他微服務的配置使用

## spring配置
spring:
    datasource: #數據庫配置
        url: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&autoReconnectForPools=true&noAccessToProcedureBodies=true&testOnBorrow=true&validationQuery=select 1
        username: root
        password: password
    jpa:
       generate-ddl: false
       hibernate:
          ddl-auto: none
          naming:
            physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
       database: mysql
       show-sql: false
    resources:
       chain:
          strategy:
             content:
                enabled: true
                paths: /**
    redis: ## Redis配置
       host: 127.0.0.1
       port: 6379
       password: password
       database: 15
       pool:
          max-active: 100
          min-idle: 2
          max-idle: 2
          max-wait: 500

#druid connect pool
db:
  druid:
     url: ${spring.datasource.url}
     username: ${spring.datasource.username}
     password: ${spring.datasource.password}
     filters: stat,wall
     max-active: 60
     initial-size: 10
     max-wait: 60000
     min-idle: 10
     time-between-eviction-runs-millis: 600000
     min-evictable-idle-time-millis: 300000
     test-while-idle: true
     test-on-borrow: false
     test-on-return: false
     pool-prepared-statements: false
     max-open-prepared-statements: 20

# 自定義配置
sysconfig:
  isDebug: true  #是否Debug
  swagger: true  #開啟swagger

 

 

6.修改pom文件(修改parent結點為父項目,刪除dependencyManagement結點(因為父項目已經引用))內容如下:

 <?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>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>1.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>config</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>config</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        <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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置中心項目結構如下:

  7.啟動配置中心微服務Config,再打開 http://localhost:808/ 會發現配置中心已經注冊成功了。

如果啟動時報錯:Caused by: org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1 

請把所有yml文件格式改為UTF-8再次啟動即可解決

 

   

四.(A方案用zuul框架).路由網關 springCloud.zuul (spring boot2.4以上不支持該框架)

1.過程與第二步一樣,(記得Spring Boot版本為2.3.6)

在選模塊需要勾選 Spring Cloud Routing 中的 Zuul

勾選Spring Cloud Discovery 中的 Eureka Discovery Client 

勾選Spring Cloud Config 中的 Config Client 

 

 

 2.給網關路由的spring boot啟動類添加注解 @EnableZuulProxy

 

 

 3.刪除resources/application.properties 新建application.yml  注意端口設置為800(可以自行修改)內容如下  

 

spring:
   profiles:
      active: ${active:dev}
   application:
      name: springCloud.zuul

server:
   port: 800
#   context-path: /zuul

#配置注冊中心的參數
eureka:
   client:
      serviceUrl:
            defaultZone: ${registry.url}
      registry-fetch-interval-seconds: 5 # 拉取服務注冊信息間隔時間 (默認為30秒)
   instance:
          lease-expiration-duration-in-seconds: 60  # 注冊中心超過這個時間沒收到心跳,會視為無效節點(默認為90秒)
          lease-renewal-interval-in-seconds: 30  # 發送心跳間隔時間(默認30秒)
          preferIpAddress: true
          instanceId: ${spring.cloud.client.ip-address}:${server.port}
      

zuul:
  add-host-header: true #webui重定向  請求頭host顯示為網關的(eg:localhost:9090)而非webui的
  ignoredServices: '*' #禁用服務名路游
  sensitive-headers:   #傳遞頭信息
  retryable: true  #負載均衡時,路游的服務重啟時,可通過重試到其他相同服務
#  host:
#     socket-timeout-millis: 60000
#     connect-timeout-millis: 60000
#zuul中網路由一定要在這里配置,不然發訪問不到微服務,getway不配置也可以訪問
  routes:
    webui:
      path: /webui/**
      serviceId: webui
    webapi:
      path: /webapi/**
      serviceId: webapi

4.再新建 application-dev.yml , application-pro.yml , application-test.yml ,三個文件一樣,當然可以根據需要修改,代碼如下:

#超時重試
ribbon:
    ReadTimeout: 300000 # 單位ms 調試時間5分鍾
    ConnectTimeout: 60000 # 單位ms 
    MaxAutoRetries: 1
    MaxAutoRetriesNextServer: 1

#超時熔斷回調
hystrix:
   command:
       default:
          execution:
             timeout:
                  enabled: true
             isolation:
                 thread:
                    timeoutInMilliseconds: 900000(300000*3) #(默認是1秒)

 5.新建bootstrap.yml 代碼如下:

spring:
    http:
        encoding:
            charset: UTF-8
            enabled: true
            force: true
    cloud:
        config:
            uri: http://${host:localhost}:809   #配置中心的地址端口
            name: config
            profile: ${active:dev} 
         

完成以后如下圖:

6.修改注冊中心的的pom文件(修改parent結點為父項目,刪除dependencyManagement結點(因為父項目已經引用))內容如下:

<?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>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>1.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>zuul</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 8.新建一個controller/testController.java代碼如下:

  

package com.example.zuul.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class testController {

    //讀取配置中心的參數
    @Value("${sysconfig.isDebug}")
    private Boolean isDebug;

    @RequestMapping("test/page1")
    public String page1(){
        return "zuul page1. current time:"+(new Date()).toString();
    }

    @RequestMapping("test/page2")
    public String page2(){return "zuul page2.sysconfig.isDebug="+isDebug.toString();}
}

zuul項目結構: 

 

9.啟動微服務zuul 打開 http://localhost:800/test/page1   與 http://localhost:800/test/page2 (顯示配置中心的參數)

  

 四.(B方案getway框架).路由網關 springCloud.theGetway (推薦該方案

 1.過程與第二步一樣,選擇模塊有

勾選 Spring Cloud Cofnig 中的 Config Server

勾選 Spring Cloud Discovery 中的 Eureka Discovery Client 

勾選 Spring Cloud Routing 中的 Geteway

 

 2.給spring boot啟動類添加注解 @EnableDiscoveryClient

 

 3.刪除resources/application.properties 新建application.yml  注意端口設置為801(可以自行修改)

在routes下面可以配置路由的微服務,默認不配置可以直接用微服務名稱也可以訪問。

內容如下

server:
  port: 801  #getway網關端口

spring:
  application:
    name: springCloud.geteway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
# 不配置routes,則默認使用服務名 ,getway不配置也可以使用spring.application.name訪問  ,zuul中網路由一定配置否則訪問不了
      routes:
        - id: webui
          uri: lb://webui
          predicates:
          - Path=/getwayWebui/**
          filters:
          - StripPrefix=1
        #以下測試用的:
        - id: service2
          uri: https://www.www.com/
          predicates:
          - Path=/baidu/**
          filters:
          - StripPrefix=1

eureka:
  client:
    service-url:
      defaultZone: ${registry.url}

4.添加resources/boostrap.yml文件內容如下

spring:
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  cloud:
    config:
      uri: http://${host:localhost}:809 #配置中心地址
      name: config
      profile: ${active:dev}

5.修改pom文件,修改parent結點,刪除Properties結點,刪除dependencyManagement結點,內容如下:

<?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>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>1.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>geteway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>geteway</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    </properties>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

6.新建controller/testController.java文件內容如下:

package com.example.geteway.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


@RestController
public class testController {

    //讀取配置中心的參數
    @Value("${sysconfig.isDebug}")
    private Boolean isDebug;

    @RequestMapping("test/page1")
    public String page1(){
        return "getway page1. current time:"+(new Date()).toString();
    }

    @RequestMapping("test/page2")
    public String page2(){return "getway page2.sysconfig.isDebug="+isDebug.toString();}
}

完成以后項目結構如下:

 

 啟動geteway網關服務,打開 http://localhost:808/ 發現getway啟動並注冊成功

 

 打開http://localhost:801/test/page2 發現geteway下的路徑可以訪問了。

 

 

五.微服務WebUI界面

1.過程與第二步一樣,選擇模塊有

勾選Spring Cloud Discovery 中的 Eureka Discovery Client 

勾選Spring Cloud Config 中的 Config Client 

勾選Web 中的 Spring Web

勾選Template Engines 中的 Thymeleaf(如果有需要就勾選)

 

  

2.給webUI的spring boot啟動類添加注解 @EnableEurekaClient

 

 

 

 

 3.刪除resources/application.properties 新建application.yml  注意端口為805 內容如下

 

spring:
   profiles:
      active: ${active:dev}
   application:
       name: webui
   thymeleaf:
           prefix: classpath:/templates/
           suffix: .html
           mode: LEGACYHTML5
           encoding: UTF-8
           content-type: text/html
           cache: false

server:
   port: 805  #微服務webui的端口

eureka:
    client:
       serviceUrl:
            defaultZone: ${registry.url}  #從配置中心讀取配置
       registry-fetch-interval-seconds: 5 # 拉取服務注冊信息間隔時間 (默認為30秒)
    instance:
          lease-expiration-duration-in-seconds: 60
          lease-renewal-interval-in-seconds: 30
          preferIpAddress: true
          instanceId: ${spring.cloud.client.ip-address}:${server.port}

4.新建bootstrap.yml代碼如下

spring:
    http:
        encoding:
            charset: UTF-8
            enabled: true
            force: true
    cloud:
        config:
            uri: http://${host:localhost}:809   #配置中心的地址
            name: config
            profile: ${active:dev}
         

5.修改pom文件(修改parent結點為父項目,刪除dependencyManagement結點(因為父項目已經引用))內容如下:

 

<?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>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>1.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>webui</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webui</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</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-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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

6.新建controller/TestUIController.java代碼如下:

package com.example.webui.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created by zhouwei on 2020-12-02
 */
@RestController
public class TestUIController {

        //讀取配置中心的參數
        @Value("${sysconfig.isDebug}")
        private Boolean isDebug;

        @RequestMapping("testUI/page1")
        public String page1(){
                return "webUI page1. current time:"+(new Date()).toString();
        }

        @RequestMapping("testUI/page2")
        public String page2(){return "webUI page2.sysconfig.isDebug="+isDebug.toString();}
}

 完成以后項目結構如下圖

 

 

7.啟動微服務webUI ,打開http://localhost:808/ 發現webui注冊成功

 

 

 

  

 8.直接訪問spring boot :http://localhost:805/testUI/page2  如下圖

   9。zuul網關800端口路由訪問,因為在zuul中的application.yml文件中的zuul.routes中配置了weui的路由。所以直接通過網關路由打開  http://localhost:800/webui/testUI/page2 會發現內容與上面一樣,這就是網關路由的作用

 

 

  geteway網關801端口下訪問,http://localhost:801/webui/testUI/page2

 

 

 

 

六.微服務WebAPI接口

 與第五步完全一樣,(記得spring boot版本先2.3.6)只是 微服務名稱 與 端口 不一樣。

在選模塊需要勾選 Spring Cloud Routing 中的 Zuul

勾選Spring Cloud Discovery 中的 Eureka Discovery Client 

勾選Web 中的 Spring Web

 yml配置文件與pom文件內容都一樣,再新建TestAPIController 內容與前面的一樣

package com.example.webapi.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class TestAPIController {

        //讀取配置中心的參數
        @Value("${sysconfig.isDebug}")
        private Boolean isDebug;

        @RequestMapping("testAPI/page1")
        public String page1(){
                return "webAPI page1. current time:"+(new Date()).toString();
        }

        @RequestMapping("testAPI/page2")
        public String page2(){return "webAPI page2.sysconfig.isDebug="+isDebug.toString();}
}

 

 所有配置完成以后項目結構如下:

 

 啟動微服務webAPI,打開http://localhost:808/ 會發現webui注冊成功

 

 通過spring boot直接訪問,打開http://localhost:806/testAPI/page2

 

通過zuul網關訪問,打開 http://localhost:800/webapi/testAPI/page2 

 

 getway網關訪問 打開http://localhost:801/webapi/testAPI/page2

 ------ 完 ------------

spring bloud demo下載 

github地址:https://github.com/smartwei/springCloudDemo.parent


免責聲明!

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



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