記錄springCloud搭建過程

概述

爲了更好的學習理解springCloud的搭建過程,在此單純記錄一下搭建過程便於理解以及往後回顧。css

項目架構

  • 一、統一依賴管理:Spring Cloud Finchley.RC1
  • 二、服務治理註冊與發現:Spring Cloud Netflix Eureka
  • 三、聲明式服務調用(服務消費者):Spring Cloud OpenFeign
  • 四、服務容錯保護限流降級(熔斷器):Spring Cloud Netflix Hystrix
  • 五、分佈式鏈路追蹤(鏈路器):Spring Cloud Zipkin
  • 六、網關路由代理調用(統一網關):Spring Cloud Gateway
  • 七、分佈式統一配置中心(配置中心):Spring Cloud Config
  • 八、服務監控:Spring Boot Amdin

一、Spring Cloud Finchley 建立統一依賴管理

Finchley :統一版本管理套件方便對jar 的版本進行管理java

一、建立文件夾spring-cloud-dependencies

二、建立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>

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

    <groupId>com.fjhckj</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>spring-cloud-dependencies</name>
    <inceptionYear>2018-Now</inceptionYear>

    <properties>
        <!-- Environment Settings -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Spring Settings -->
        <spring-cloud.version>Finchley.RC1</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>

    <build>
        <plugins>
            <!-- Compiler 插件, 設定 JDK 版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>

            <!-- 打包 jar 文件時,配置 manifest 文件,加入 lib 包的 jar 依賴 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <addMavenDescriptor>false</addMavenDescriptor>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <configuration>
                            <archive>
                                <manifest>
                                    <!-- Add directory entries -->
                                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                                    <addClasspath>true</addClasspath>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <!-- resource -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
            </plugin>

            <!-- install -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-install-plugin</artifactId>
            </plugin>

            <!-- clean -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
            </plugin>

            <!-- ant -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
            </plugin>

            <!-- dependency -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
            </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <!-- Java Document Generate -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>prepare-package</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

                <!-- YUI Compressor (CSS/JS壓縮) -->
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>yuicompressor-maven-plugin</artifactId>
                    <version>1.5.1</version>
                    <executions>
                        <execution>
                            <phase>prepare-package</phase>
                            <goals>
                                <goal>compress</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <encoding>UTF-8</encoding>
                        <jswarn>false</jswarn>
                        <nosuffix>true</nosuffix>
                        <linebreakpos>30000</linebreakpos>
                        <force>true</force>
                        <includes>
                            <include>**/*.js</include>
                            <include>**/*.css</include>
                        </includes>
                        <excludes>
                            <exclude>**/*.min.js</exclude>
                            <exclude>**/*.min.css</exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <!-- 資源文件配置 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>

    <repositories>
        <repository>
            <id>aliyun-repos</id>
            <name>Aliyun Repository</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>

        <repository>
            <id>sonatype-repos</id>
            <name>Sonatype Repository</name>
            <url>https://oss.sonatype.org/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>sonatype-repos-s</id>
            <name>Sonatype Repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>

        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-repos</id>
            <name>Aliyun Repository</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>
複製代碼

三、託管pom 下載maven

二、Spring Cloud Netflix Eureka 服務治理註冊與發現

eureka:分佈式架構中多服務之間接口互相調用,須要記錄各個服務之間的ip端口等信息,使用eureka 後能夠將ip端口等交由eureka託管,服務之間訪問時只須要經過服務名稱進行調用便可。react

一、建立服務註冊中心

一、建立基礎spring-boot項目

二、增長eureka依賴

<!-- Spring Cloud Eureka Begin -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    <!-- Spring Cloud Eureka end -->
複製代碼

三、繼承pom至統一依賴管理

<parent>
        <groupId>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>
複製代碼

完整pom.xml文件以下git

<?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>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-eureka</artifactId>
    <name>spring-cloud-eureka</name>
    <packaging>jar</packaging>



    <dependencies>
        <!-- Spring Boot Begin -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <!-- Spring Boot End -->

        <!-- Spring Cloud Begin -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!-- Spring Cloud End -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.fjhckj.springcloudeureka.SpringCloudEurekaApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
複製代碼

三、在Application中增長註解@EnableEurekaServer

四、配置文件設置

#服務名稱
spring:
  application:
    name: spring-cloud-eureka
#服務端口
server:
  port: 8081

#eureka.client.registerWithEureka:false
#eureka.client.fetchRegistry:false
#代表是eureka服務端
#eureka.client.serviceUrl.defaultZone 網關注冊地址
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

複製代碼

五、啓動eureka測試eureka網關是否能進入

三、聲明式服務調用:Spring Cloud OpenFeign(服務消費者)

feign:各個服務之間的調用的封裝,使調用其餘服務的代碼更加優雅。feign 集成了 中集成了ribbon 方式調用其餘服務接口,還集成了 hystrix 熔斷器 web

一、建立服務提供者

一、建立基礎springboot項目
二、繼承pom至統一依賴管理
三、增長eureka依賴
<!-- Spring Cloud Begin -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    <!-- Spring Cloud End -->
複製代碼
四、完整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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-service</artifactId>
    <packaging>jar</packaging>

    <name>spring-cloud-service</name>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Cloud Begin -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!-- Spring Cloud End -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.fjhckj.springcloudservice.SpringCloudServiceApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
複製代碼
五、設置配置文件
#spring.application.name 服務名稱
spring:
  application:
    name: spring-cloud-service
#server.port 端口
server:
  port: 8082
# eureka.client.serviceUrl.defaultZone eureka網關注冊地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/

複製代碼
六、增長eureka客戶端註解

@EnableEurekaClient spring

七、建立restfull接口供消費者使用

八、啓動提供者

九、經過eureka提供的服務地址訪問接口

二、建立服務消費者經過feign方式調用提供者接口

一、建立基礎spring-boot項目
二、繼承pom至統一依賴管理
三、增長pom依賴內容以下
<!--feign Begin-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
     <!--feign End-->
複製代碼
四、完整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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-feign</artifactId>
    <name>spring-cloud-feign</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--feign Begin-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--feign End-->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.fjhckj.springcloudfeign.SpringCloudFeignApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
複製代碼
五、修改配置文件
spring:
  application:
    name: spring-cloud-feign

server:
  port: 8083

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/

#解決使用feign訪問服務提供者時找不到提供者的問題
ribbon:
  eureka:
    enabled: true
複製代碼
六、增長註解@EnableEurekaClient eureka客戶端註解、@EnableFeignClients feign註解

七、建立消費接口調用提供者接口
一、建立FeignSerivice接口

增長@FeignClient(value = "spring-cloud-service") 註解 value 爲服務網關eureka網關注冊的Application名稱apache

增長抽象方法編程

String helloWorld(@RequestParam("message") String message);
複製代碼
ps:注意增長@RequestParam不然參數會報錯
複製代碼

抽象方法上增長@RequestMapping(value = "spring-cloud-service/hello-world", method = RequestMethod.GET) 對應提供者的接口地址json

二、建立提供者rest接口調用service的方法

八、啓動消費者測試接口狀況

九、Feign 自動實現負載均衡測試
一、提供者中輸出端口號
二、開啓兩個提供者提供服務 端口號分別爲8082:8084

三、測試結果-1

四、測試結果-2

十、Feign 中集成了ribbon 順道測試一下

ps:其中有坑在使用ribbon時注意服務名稱是要與配置文件中的spring.application.name 一致 使用Feign時則可使用eureka 網關上的application 名稱 數組

四、服務容錯保護限流降級:Spring Cloud Netflix Hystrix(熔斷器)

爲了保證其高可用,單個服務一般會集羣部署。因爲網絡緣由或者自身的緣由,服務並不能保證 100% 可用,。當對特定的服務的調用的不可用達到一個閥值時將觸發熔斷返回fallback的方法實現值。

一、feign 中使用熔斷器

一、配置文件中開啓hystrix
#開啓feign 支持熔斷器
feign:
  hystrix:
    enabled: true
複製代碼
二、建立FeignServiceImp 實現類 實現 FeignService 並交由spring託管

三、FeignService @FeignClient 註解 增長fallback = FeignServiceImp.class

四、測試熔斷器
一、服務提供者狀態正常下結果

二、關閉提供者後測試結果

五、斷點後無心間看到熔斷反射的堆棧信息順道作個記錄

二、熔斷監控

一、feign 項目增長依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
複製代碼
二、開啓註解支持@EnableHystrixDashboard

三、關閉spring-cloud-service 觸發feign 熔斷並進入HystrixDashboard監控頁面查看結果

http://127.0.0.1:8083/hystrix

五、分佈式鏈路追蹤(鏈路器):Spring Cloud Zipkin

隨着服務的愈來愈多,對調用鏈的分析會愈來愈複雜服務的調用關係多是這樣

爲了更清晰的管理服務之間的調用關係使用鏈路追蹤

一、建立基礎boot

二、繼承統一管理pom

三、增長zipkin依賴

<dependency>
            <groupId>io.zipkin.java</groupId>
            <artifactId>zipkin-server</artifactId>
            <version>${zipkin.version}</version>
        </dependency>
        <dependency>
            <groupId>io.zipkin.java</groupId>
            <artifactId>zipkin-autoconfigure-ui</artifactId>
            <version>${zipkin.version}</version>
        </dependency>
複製代碼

版本爲2.12.0

完整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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-zipkin</artifactId>
    <packaging>jar</packaging>

    <name>spring-cloud-zipkin</name>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.zipkin.java</groupId>
            <artifactId>zipkin-server</artifactId>
            <version>${zipkin.version}</version>
        </dependency>
        <dependency>
            <groupId>io.zipkin.java</groupId>
            <artifactId>zipkin-autoconfigure-ui</artifactId>
            <version>${zipkin.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.fjhckj.springcloudzipkin.SpringCloudZipkinApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
複製代碼

四、修改配置文件

spring:
  application:
    name: spring-cloud-zipkin


server:
  port: 8084

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/

management:
  metrics:
    web:
      server:
        auto-time-requests: false
複製代碼

五、開啓註解支持@EnableZipkinServer

六、除zipkin與統一管理 之外全部的模塊須要被zipkin 監控

pom中增長

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>
複製代碼

配置文件增長

spring:
  zipkin:
    base-url: http://localhost:8084
複製代碼

七、測試zipkin 追蹤服務鏈路

六、網關路由代理調用(統一網關):Spring Cloud Gateway

因爲服務過多對外暴露的接口可能也有不少,爲了統一管控使用統一網關進行代理,這樣只需向外暴露一個端口,根據不一樣的服務名網關進行對應服務的調用。

一、gateway實現簡單路由

一、建立spring-boot

二、繼承統一管理pom

三、增長依賴

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
複製代碼

四、完整依賴

<?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>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-gateway</artifactId>
    <packaging>jar</packaging>

    <name>spring-cloud-gateway</name>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.fjhckj.springcloudgateway.SpringCloudGatewayApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
複製代碼

五、修改配置文件

spring:
  application:
    #服務名稱
    name: SPRING-CLOUD-GATEWAY
  zipkin:
    #zipkin服務地址
    base-url: http://localhost:8084
  cloud:
    gateway:
      discovery:
        locator:
          #開啓支持eureka以服務名形式調用
          enabled: true
      routes:
          # 自定義服務名稱:ps:特殊名稱擁有特殊做用如after_route、before_route、between_route
        - id: SPRING-CLOUD-FEIGN
          #lb:以LoadBalancerClient形式調用請求 SPRING-CLOUD-FEIGN eureka上註冊的服務名
          uri: lb://SPRING-CLOUD-FEIGN
          predicates:
            #匹配get post 請求
            - Method=GET,POST
        - id: SPRING-CLOUD-SERVICE
          uri: lb://SPRING-CLOUD-SERVICE
          predicates:
            - Method=GET,POST
server:
  port: 8085

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/  # eureka 服務註冊地址

![](https://user-gold-cdn.xitu.io/2019/5/18/16ac6e5dd1c1960d?w=1565&h=854&f=png&s=155703)

複製代碼

六、啓動gateway 網關由網關統一訪問 feign 與 service 兩個服務

一、網關訪問feign 狀況

二、網關訪問service 狀況

七、遇到的坑

一、gateway spring-boot-starter-webflux 與 spring-boot-starter-tomcat jar包衝突,刪除下圖jar包

ps:每次刷新都會出來這幾個jar
複製代碼

解決方案: Ctrl + shift + Alt + U 找到類依賴關係pom 中排除

<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
複製代碼
三、網關調用時要按照eureka上註冊的名稱而是不yml 中配置的名稱爲了統一將全部的yml 中配置的服務名稱所有大寫

二、gateway 實現簡單全局過濾功能

package com.fjhckj.springcloudgateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定義全局過濾器
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //獲取參數
        String token =  exchange.getRequest().getQueryParams().getFirst("token");
        if (StringUtils.isBlank(token)) {
            ServerHttpResponse response = exchange.getResponse();
            Map<String,Object> resuMap = new HashMap<>();
            resuMap.put("status", -1);
            resuMap.put("massage", "鑑權失敗");
            //轉化爲json 並轉爲字節數組
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] data = new byte[0];
            try {
                data = objectMapper.writeValueAsBytes(resuMap);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            // 輸出錯誤信息到頁面
            DataBuffer buffer = response.bufferFactory().wrap(data);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //filter執行的優先級,值越小則優先級越大
        return 0;
    }
}
複製代碼

gateway 更多自定義過濾方式 gateway 更多自定義過濾方式

三、gateway 實現全局熔斷

一、增長依賴
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
複製代碼
二、完整配置文件
spring:
  application:
    #服務名稱
    name: SPRING-CLOUD-GATEWAY
  zipkin:
    #zipkin服務地址
    base-url: http://localhost:8084
  cloud:
    gateway:
      discovery:
        locator:
          #開啓支持eureka以服務名形式調用
          enabled: true
      routes:
          # 自定義服務名稱:ps:特殊名稱擁有特殊做用如after_route、before_route、between_route
        - id: SPRING-CLOUD-FEIGN
          #lb:以LoadBalancerClient形式調用請求 SPRING-CLOUD-FEIGN eureka上註冊的服務名
          uri: lb://SPRING-CLOUD-FEIGN
          predicates:
            #匹配get post 請求
            - Method=GET,POST

        - id: SPRING-CLOUD-SERVICE
          uri: lb://SPRING-CLOUD-SERVICE
          predicates:
            - Method=GET,POST
      #全局熔斷服務爲響應或響應超時觸發熔斷
      default-filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/defaultfallback


# hystrix 信號量隔離,3秒後自動超時
hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 3000
  shareSecurityContext: true



server:
  port: 8085

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/  # eureka 服務註冊地址

複製代碼

主要增長

三、熔斷回調接口
package com.fjhckj.springcloudgateway.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 默認熔斷處理
 */
@RestController
public class DefaultHystrixController {

    @RequestMapping("/defaultfallback")
    public Map<String,String> defaultfallback(){
        Map<String,String> map = new HashMap<>();
        map.put("resultCode","error");
        map.put("resultMessage","網絡鏈接超時");
        map.put("resultObj","null");
        return map;
    }
}
複製代碼

四、測試熔斷

七、分佈式統一配置中心(配置中心):Spring Cloud Config

Spring Cloud Config:在分佈式系統中,因爲服務數量巨多,爲了方便服務配置文件的統一管理,實時更新而產生的組件。

一、服務端

一、基礎項目繼承pom

二、pom 增長

<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
</dependency>
複製代碼

三、完整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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-config</artifactId>
    <packaging>jar</packaging>

    <name>spring-cloud-config</name>

    <dependencies>
        <!-- Spring Boot Begin -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot End -->

        <!-- Spring Cloud Begin -->
        <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-server</artifactId>
        </dependency>
        <!-- Spring Cloud End -->
    </dependencies>

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

</project>
複製代碼

四、配置文件

spring:
  application:
    #服務名
    name: SPRING-CLOUD-CONFIG
  cloud:
    config:
      #倉庫分支
      label: master
      server:
        git:
          # git 地址
          uri: xxx
          # 文件夾
          search-paths: xxx
          # git 帳戶
          username: xxx
          # git 密碼
          password: xxx
          # 雲配置拉取的緩存路徑
          basedir: xxx



server:
  port: 8888

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/
複製代碼

五、啓動類增長註解@EnableConfigServer

六、測試文件訪問

文件映射支持以下幾種方式

http://ip:port/{application}/{profile}[/{label}]
http://ip:port/{application}-{profile}.yml
http://ip:port/{label}/{application}-{profile}.yml
http://ip:port/{application}-{profile}.properties
http://ip:port/{label}/{application}-{profile}.properties
複製代碼

二、客戶端

一、增長pom

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
     </dependency>
    
複製代碼

二、因爲使用雲配置因此配置文件修改以下

spring:
  cloud:
    config:
      uri: http://localhost:8888
      name: serviceApplication
      label: master
      profile: dev
複製代碼

三、測試客戶端獲取雲配置

倉庫下擁有配置文件以下

兩個文件serviceApplication-dev與serviceApplication-test端口分別爲8082:9082

三、遇到的坑 yml 中定義的數組形式參數被轉換爲

spring.cloud.gateway.routes[0].id=SPRING-CLOUD-FEIGN 以後在客戶端中獲取改文件時報錯

Could not locate PropertySource: Error while extracting response for type [class org.springframework.cloud.config.environment.Environment] and content type [application/xml;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character '[' (code 91) excepted space, or '>' or "/>"
 at [row,col {unknown-source}]: [1,593]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character '[' (code 91) excepted space, or '>' or "/>"
複製代碼

解決方法未知

斷點跟蹤至

解析下一個屬性名時拋出異常

八、服務監控:Spring Boot Amdin

隨着服務愈來愈多對於各個微服務系統的健康狀態、會話數量、併發數、服務資源、延遲等度量信息的收集就成爲了一個挑戰,spring boot admin 爲此而生。

一、服務端

一、基礎項目繼承pom

二、增長pom

${spring-cloud-admin.version} 爲 2.0.0

<dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>${spring-cloud-admin.version}</version>
    </dependency>
複製代碼

三、完整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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.fjhckj</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>spring-cloud-admin</artifactId>
    <packaging>jar</packaging>

    <name>spring-cloud-admin</name>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>${spring-cloud-admin.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
    </dependencies>

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

</project>
複製代碼

四、配置文件

spring:
  application:
    name: SPRING-CLOUD-ADMIN
  zipkin:
    base-url: http://localhost:8084

server:
  port: 8087

management:
  endpoint:
    health:
      show-details: always
  endpoints:
    web:
      exposure:
        include: health,info

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/
複製代碼

二、客戶端

一、增長pom

<dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>${spring-cloud-admin.version}</version>
    </dependency>
複製代碼

二、增長配置文件

spring:
    boot:
        admin:
          client:
            # spring-clouda-dmin 監控地址
            url: http://localhost:8087
複製代碼

三、開啓全部服務測試監控效果

除admin 自己外全部服務均上線

本篇完結

一、該篇總結

整套系統的搭建大概耗時一週,固然只有晚上幾個小時的時間,基本上搭建的時間都在集成gateway 網關上與config 配置中心上了,學習過程當中又出現不少新名例如 :響應式編程、netty 等,越學感受不會的越多.... 搭建過程當中也遇到各類奇葩問題什麼大小寫名稱啦,特殊字符啦七七八八的,不過好在系統最終仍是搭起來了....

二、參考了太多的博客這邊就不列了偷個懶

相關文章
相關標籤/搜索