springboot-zuul閘道器

╰煙消雲散發表於2020-12-13

Zuul路由閘道器簡介及基本使用

簡介

在這裡插入圖片描述
請看上圖,這裡的API 路由閘道器服務 由Zuul實現,主要就是對外提供服務介面的時候,起到了請求的路由和過濾作用,也因此能夠隱藏內部服務的介面細節,從來有利於保護系統的安全性;

路由配置

Zuul 路由配置

這裡我們的zuul也註冊到eureka服務裡,埠3001;

我們修改下Hosts,專門為我們新建一個module microservice-zuul-3001

zuul搞個本地域名對映

hosts檔案 加下:
在這裡插入圖片描述
然後pom.xml要加上:

<!--zuul閘道器-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>

完整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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.liyingdong</groupId>
        <artifactId>t243microservice</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>microservice-zuul-3001</artifactId>

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

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

        <!-- actuator監控 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- hystrix容錯 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!--zuul閘道器-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>

        <!--ribbon相關依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <!--引入Feign依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>

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

搞一個 application.yml (完整的)


server:
  port: 3001
  context-path: /
spring:
  application:
    name: microservice-zuul
eureka:
  instance:
    instance-id: microservice-zuul:3001
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.liyingdong.com:2001/eureka/,http://eureka2002.liyingdong.com:2002/eureka/,http://eureka2003.liyingdong.com:2003/eureka/
info:
  groupId: com.liyingdong.testSpringcloud
  artifactId: microservice-zuul-3001
  version: 1.0-SNAPSHOT
  userName: http://liyingdong.com
  phone: 123456


feign:
  hystrix:
    enabled: true

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 15000
ribbon:
  ReadTimeout: 6000
  ConnectTimeout: 6000
  MaxAutoRetries: 0
  MaxAutoRetriesNextServer: 1
  eureka:
    enabled: true

zuul:
  routes:
    studentServer.serviceId: microservice-student
    studentServer.path: /studentServer/**
  ignored-services: "*"
  prefix: /liyingdong

主啟動類:ZuulApplication_3001加下@EnableZuulProxy註解

package com.liyingdong.microservicezuul3001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableZuulProxy
public class MicroserviceZuul3001Application {

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

}

我們測試下:
啟動三個eureka 然後再啟動下一個1001服務,以及 zuul閘道器服務;

在這裡插入圖片描述
我們直接請求:http://localhost:1001/student/list 能獲取到資料;
我們用 http://zuul.liyingdong.com:3001/microservice-student/student/list 域名+埠+服務名稱+請求地址 也能請求到資料;

說明我們的路由基本配置OK

Zuul路由對映配置

上面是zuul的簡單使用,從介面地址很輕易的就暴露了服務提供者的唯一標識名microservice-student;有安全風險,我們需要將其隱藏;

ignored-services的作用是將原來的服務提供者唯一標識名禁用;

Prefix的作用是給服務加字首

yml檔案中新增以下配置:

zuul:
  routes:
    studentServer.serviceId: microservice-student
    studentServer.path: /studentServer/**
  ignored-services: "*"
  prefix: /liyingdong

配置完畢後可通過以下連結做測試

http://zuul.liyingdong.com:3001/microservice-student/student/list
http://zuul.liyingdong.com:3001/studentServer/student/list
http://zuul.liyingdong.com:3001/liyingdong/microservice-student/student/list
http://zuul.liyingdong.com:3001/liyingdong/studentServer/student/list

在這裡插入圖片描述
對應的配置會出現上面的錯誤頁面,這是正常現象。

ZuulFallBack

Zuul作為服務閘道器為了保證自己不被服務拖垮,本身已經整合了Hystrix對路由轉發進行隔離。 為了方便開發人員對服務短路進行自定義處理,

package com.liyingdong.microservicezuul3001.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;

@Component
public class ZuulFallBack implements ZuulFallbackProvider {

    @Override
    public String getRoute() {
        return "*";
    }

    /**
     * 在給zuul整合回退功能時,只要類實現ZuulFallbackProvider介面,並且註冊bean即可。
     *
     * 不過需要注意的時,這個回退只有服務掉線或者超時的情況下才會觸發(Camden.SR4版本測試是這樣),
     * 如果服務程式出現異常,此回退程式是不能處理的,異常會直接返回給呼叫者,比如頁面。
     *
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//application/json;charset=UTF-8
                return headers;
            }

            @Override
            public InputStream getBody() throws IOException {
                String msg = "服務繁忙,請稍後.....";
                //new ByteArrayInputStream("{\"code\":-1,\"msg\":\"服務暫不可用\"}".getBytes(StandardCharsets.UTF_8))
                return new ByteArrayInputStream(msg.getBytes());
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.BAD_REQUEST.getReasonPhrase();//400
            }

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST.value();//"Bad Request"
            }

            @Override
            public void close() {

            }
        };
    }
}

回退做了處理
在這裡插入圖片描述

zuul超時時間設定

http://zuul.liyingdong.com:3001/microservice-student/student/hystrix,只能呼叫響應時間不超過一秒的方法 ,因為hystrix方法裡面設定的休眠時間是1.1秒,而zuul的預設是1秒所有會出現以上圖片現象

yml檔案加入

feign:
  hystrix:
    enabled: true

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 15000
ribbon:
  ReadTimeout: 6000
  ConnectTimeout: 6000
  MaxAutoRetries: 0
  MaxAutoRetriesNextServer: 1
  eureka:
    enabled: true

Zuul請求過濾配置

比如我們登入某個系統 需要身份驗證,使用者名稱密碼啥的;

我們請求服務,也可以來設定身份驗證,也就是過濾非法請求;Zuul通過ZuulFilter過濾器實現;
一般具體實現的話 每次經過Zuul服務閘道器 我們都對帶來的token進行有效性驗證;

我們先定義一個 AccessFilter類:

package com.liyingdong.microservicezuul3001.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 小李飛刀
 * @site www.javaxl.com
 * @company
 * @create  2019-04-30 16:05
 */
public class AccessFilter extends ZuulFilter {

    Logger logger=Logger.getLogger(AccessFilter.class);

    /**
     * 判斷該過濾器是否要被執行
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 過濾器的具體執行邏輯
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String parameter = request.getParameter("accessToken");
        logger.info(request.getRequestURL().toString()+" 請求訪問");
        if(parameter==null){
            logger.error("accessToken為空!");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");
            return null;
        }
        //  token判斷邏輯
        logger.info(request.getRequestURL().toString()+" 請求成功");
        return null;
    }

    /**
     * 過濾器的型別 這裡用pre,代表會再請求被路由之前執行
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 過濾器的執行順序
     */
    @Override
    public int filterOrder() {
        return 0;
    }

}

ZuulConfig 隨著springboot專案啟動而載入我們的自定義過濾器

package com.liyingdong.microservicezuul3001;

import com.liyingdong.microservicezuul3001.filter.AccessFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZuulConfig {

    @Bean
    public AccessFilter accessFilter(){
        return new AccessFilter();
    }
}

瀏覽器輸入地址進行測試

不帶token的情況

http://zuul.liyingdong.com:3001/liyingdong/studentServer/student/list

在這裡插入圖片描述
帶token的情況

http://zuul.liyingdong.com:3001/liyingdong/studentServer/student/list?accessToken=zs

在這裡插入圖片描述

相關文章