【spring cloud】 網關Zuul(過濾:安全、監控、限流、路由)

單點搭建


注意:藍色虛線代表註冊;綠色虛線代表調用、紅色虛線代表心跳

1.     添加依賴
創建項目tcloud-gateway-zuulserver , pom.xml內容如下

<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> com.svw.tbox.tcloud.gateway</groupId>

    <artifactId>tcloud-gateway-zuulserver</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <name>tcloud-gateway-zuulserver</name>

    <url>http://maven.apache.org</url>



    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>1.4.3.RELEASE</version>

    </parent>



    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

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

    </properties>



    <dependencies>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-eureka</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-zuul</artifactId>

        </dependency>

    </dependencies>

    <!-- 引入spring cloud的依賴 -->

    <dependencyManagement>

        <dependencies>

            <dependency>

                <groupId>org.springframework.cloud</groupId>

                <artifactId>spring-cloud-dependencies</artifactId>

                <version>Camden.SR4</version>

                <type>pom</type>

                <scope>import</scope>

            </dependency>

        </dependencies>

    </dependencyManagement>

</project>

2.     啓動類開啓zuul

package com.svw.tbox.tcloud.gateway.zuul;



import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.zuul.EnableZuulProxy;



@SpringBootApplication

@EnableZuulProxy

publicclass ZuulApplication {

    publicstaticvoid main(String[] args) {

        SpringApplication.run(ZuulApplication.class, args);

    }

}

3.     application.yml配置端口和註冊到eurekaserver

server:

  port: 8200

spring:

  application:

    name: tcloud-gateway-zuulserver

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/

  instance:

    prefer-ip-address:true

4.     效果
啓動tcloud-user-eurekaserver 2個實例進程

啓動tcloud-user-provider 2個實例進程

啓動tcloud-user-consumer 1個實例進程

啓動tcloud-gateway-zuulserver

 

訪問http://localhost:8200/tcloud-user-consumer/user/hrf ,

請求會被Zuul轉發到http://localhost:9000/user/hrf


訪問http://localhost:8200/tcloud-user-provider/getUser ,

請求會被Zuul轉發到http://localhost:8000/getUser

ü  小結

前提條件:

Eureka Server註冊的微服務的serviceId 在此處簡稱ms_id ;

Eureka Server註冊的微服務的IP 在此處簡稱 ms_ip ;

Eureka Server註冊的微服務的端口號 在此處簡稱 ms_port 。

Zuul轉發規則是:

http://網關IP地址:網關端口號/ms_id/**

會被轉發到 =》

http:// ms_ip: ms_port/**


1.     高可用
原理:

Zuul 作爲 Eureka Client ,創建多個ZuulEureka Client註冊到Eureka Server集羣

=>將多個Zuul節點註冊到eureka sever

操作:

1.tcloud-gateway-zuulserver修改依賴pom.xml改成:

server:

  port: 8200

spring:

  application:

    name: tcloud-gateway-zuulserver

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/,http://localhost:8101/eureka/

  instance:

    prefer-ip-address:true

 

複製tcloud-gateway-zuulserver 項目 ,命名tcloud-gateway-zuulserver2修改 pom.xml

server:

  port: 8201

spring:

  application:

    name: tcloud-gateway-zuulserver

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/,http://localhost:8101/eureka/

  instance:

    prefer-ip-address:true

啓動兩個zuul server

=》重啓provider和consumer微服務 ,運行效果和單節點一樣

2.     容錯:Zuul回退
如果微服務下線了,針對每個微服務,都需要回復一箇中文提示,而不是報異常1.     修改zuul server
1.      針對微服務tcloud-user-consumer添加回退類

package com.svw.tbox.tcloud.gateway.zuul.fallback;



import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.client.ClientHttpResponse;

import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.nio.charset.Charset;



@Component

public class ConsumerFallbackProvider implements ZuulFallbackProvider {

  @Override

  public String getRoute() {

    // 表明是爲哪個微服務提供回退

    return "tcloud-user-consumer";

  }



  @Override

  public ClientHttpResponse fallbackResponse() {

    return new ClientHttpResponse() {

      @Override

      public HttpStatus getStatusCode() throws IOException {

        // fallback時的狀態碼

        return HttpStatus.OK;

      }



      @Override

      public int getRawStatusCode() throws IOException {

        // 數字類型的狀態碼,本例返回的其實就是200,詳見HttpStatus

        return this.getStatusCode().value();

      }



      @Override

      public String getStatusText() throws IOException {

        // 狀態文本,本例返回的其實就是OK,詳見HttpStatus

        return this.getStatusCode().getReasonPhrase();

      }



      @Override

      public void close() {

      }



      @Override

      public InputStream getBody() throws IOException {

        // 響應體

        return new ByteArrayInputStream("tcloud-user-consumer微服務不可用,請稍後再試。".getBytes());

      }



      @Override

      public HttpHeaders getHeaders() {

        // headers設定

        HttpHeaders headers = new HttpHeaders();

        MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));

        headers.setContentType(mt);

        return headers;

      }

    };

  }

}

2.     效果
按照如下順序啓動:

=> tcloud-base-eurekaserver

=>tcloud-commons-configserver

=>tcloud-gateway-zuulserver

=>tcloud-user-provider

=>tcloud-user-consumer

關閉:tcloud-user-consumer

訪問http://localhost:8200/tcloud-user-consumer/log-instance 出現如下效果:

1.     動態路由
參考3.9.4配置文件動態更新,將網關作爲一個config client,註冊到Eureka、config server ,連接到kafka。

1.     Pom.xml添加依賴
       <dependency>

           <groupId>org.springframework.cloud</groupId>

           <artifactId>spring-cloud-starter-eureka</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-bus-kafka</artifactId> 

        </dependency>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-configuration-processor</artifactId>

           <optional>true</optional>

       </dependency>

2.     添加配置參數
eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/

  instance:

    prefer-ip-address:true

server:

  port: 8200

spring:

  application:

    name: tcloud-gateway

  cloud:

    stream:

      default-binder: kafka

      kafka:

        binder:

          zk-nodes: localhost:2181

          brokers: localhost:9092

    config:

      failFast:true

      profile: local

      label: develop

      discovery:

        enabled:true

        serviceId: tcloud-commons-config-server

3.     啓動類中註冊自動配置bean @RefreshScope
@SpringBootApplication

@EnableZuulProxy

@EnableFeignClients

@EnableHystrix

publicclass GatewayApplication {

    publicstaticvoid main(String[] args) {

       SpringApplication.run(GatewayApplication.class, args);

    }

   

    @RefreshScope

    @ConfigurationProperties("zuul")

    public ZuulProperties zuulProperties() {

       returnnew ZuulProperties();

    }

}

4.     配置路由參數
zuul:

  add-host-header:true

  routes:

    tcloud-security-auth: /auth/**

    tcloud-commons-config-server: /config/**

tcloud-gateway: /gateway/**

management:

  security:

    enabled:false

 

5.     效果
1.      開啓基礎服務
開啓zookeeper、kafka

2.      寫一個微服務測試controller
tcloud-security-auth ,訪問地址是:http://localhost:8200/auth/mqtt/profile

@RefreshScope

@RestController

@RequestMapping("/mqtt")

publicclass MqttController {

    @Value("${profile}")

    private String profile;

   

    @RequestMapping(value = "/profile", method = RequestMethod.GET)

    public String profile() {

       returnprofile;

    }

……

3.      修改路由地址
zuul:

  add-host-header:true

  routes:

    tcloud-security-auth: /check/**

    tcloud-commons-config-server: /config/**

tcloud-gateway: /gateway/**

management:

  security:

    enabled:false

4.      請求自動刷新參數
訪問: http://localhost:8300/bus/refresh

5.      再次請求
訪問:http://localhost:8200/check/mqtt/profile


--------------------- 
作者:行一米 
來源:CSDN 
原文:https://blog.csdn.net/baidu_36415076/article/details/79533572 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章