史上最簡單的SpringCloud教程 | 第五篇: 路由網關(zuul)(Finchley版本)

轉載請標明出處:
原文首發於:https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f5-zuul/
本文出自方誌朋的博客html

在微服務架構中,須要幾個基礎的服務治理組件,包括服務註冊與發現、服務消費、負載均衡、斷路器、智能路由、配置管理等,由這幾個基礎組件相互協做,共同組建了一個簡單的微服務系統。一個簡答的微服務系統以下圖:git

Azure (1).png
注意:A服務和B服務是能夠相互調用的,做圖的時候忘記了。而且配置服務也是註冊到服務註冊中心的。github

在Spring Cloud微服務系統中,一種常見的負載均衡方式是,客戶端的請求首先通過負載均衡(zuul、Ngnix),再到達服務網關(zuul集羣),而後再到具體的服。,服務統一註冊到高可用的服務註冊中心集羣,服務的全部的配置文件由配置服務管理(下一篇文章講述),配置服務的配置文件放在git倉庫,方便開發人員隨時改配置。web

1、Zuul簡介

Zuul的主要功能是路由轉發和過濾器。路由功能是微服務的一部分,好比/api/user轉發到到user服務,/api/shop轉發到到shop服務。zuul默認和Ribbon結合實現了負載均衡的功能。spring

zuul有如下功能:sql

  • Authentication
  • Insights
  • Stress Testing
  • Canary Testing
  • Dynamic Routing
  • Service Migration
  • Load Shedding
  • Security
  • Static Response handling
  • Active/Active traffic management

2、準備工做

繼續使用上一節的工程。在原有的工程上,建立一個新的工程。apache

3、建立service-zuul工程

其pom.xml文件以下:api

<?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>com.forezp</groupId>
    <artifactId>service-zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>service-zuul</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.forezp</groupId>
        <artifactId>sc-f-chapter5</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

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

在其入口applicaton類加上註解@EnableZuulProxy,開啓zuul的功能:瀏覽器

@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceZuulApplication {

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

加上配置文件application.yml加上如下的配置代碼:安全

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul
zuul:
  routes:
    api-a:
      path: /api-a/**
      serviceId: service-ribbon
    api-b:
      path: /api-b/**
      serviceId: service-feign

首先指定服務註冊中心的地址爲http://localhost:8761/eureka/,服務的端口爲8769,服務名爲service-zuul;以/api-a/ 開頭的請求都轉發給service-ribbon服務;以/api-b/開頭的請求都轉發給service-feign服務;

依次運行這五個工程;打開瀏覽器訪問:http://localhost:8769/api-a/hi?name=forezp ;瀏覽器顯示:

hi forezp,i am from port:8762

打開瀏覽器訪問:http://localhost:8769/api-b/hi?name=forezp ;瀏覽器顯示:

hi forezp,i am from port:8762

這說明zuul起到了路由的做用

4、服務過濾

zuul不只只是路由,而且還能過濾,作一些安全驗證。繼續改造工程;

@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        log.info("ok");
        return null;
    }
}
  • filterType:返回一個字符串表明過濾器的類型,在zuul中定義了四種不一樣生命週期的過濾器類型,具體以下:
    • pre:路由以前
    • routing:路由之時
    • post: 路由以後
    • error:發送錯誤調用
  • filterOrder:過濾的順序
  • shouldFilter:這裏能夠寫邏輯判斷,是否要過濾,本文true,永遠過濾。
  • run:過濾器的具體邏輯。可用很複雜,包括查sql,nosql去判斷該請求到底有沒有權限訪問。

這時訪問:http://localhost:8769/api-a/hi?name=forezp ;網頁顯示:

token is empty

訪問 http://localhost:8769/api-a/hi?name=forezp&token=22
網頁顯示:

hi forezp,i am from port:8762

本文源碼下載:
https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter5

5、參考資料:

http://blog.csdn.net/forezp/article/details/69939114

http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html


掃碼關注有驚喜

(轉載本站文章請註明做者和出處 方誌朋的博客

相關文章
相關標籤/搜索