SpringCloud:網關服務(Zuul)

1、Zuul簡介
Zuul作爲微服務系統的網關組件,用於構建邊界服務(Edge Service),致力於動態路由、過濾、監控、彈性伸縮和安全。其在微服務架構中有着重要的作用,主要體現在以下六個方面:

  • Zull、Ribbon以及Eureka相結合可以實現智能路由和負載均衡的功能,Zull可以按照某種策略將請求分發到不同的實例上
  • 網關作爲邊界服務,將內部服務的API接口進行聚合並統一對外暴露接口。保護內部服務的API接口,防止內部服務被外界調用泄露敏感信息;
  • 網關可以對用戶的身份權限進行認證,防止非法請求API接口;
  • 網關可以實現監控功能,實時日誌輸出,對請求進行記錄;
  • 網關可以用來實現流量監控,在高流量的情況下,對服務進行降級;
  • API接口從內部服務分離出來,便於測試

2、創建一個Zuul工程作爲網關
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>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>service-zuul</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>service-zuul</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</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-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</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>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
		</repository>
	</repositories>

</project>

application.yml,這裏配置了兩種路由,以ribbon開頭的請求都會轉發到實例service-ribbon上,以feign開頭的請求會轉發到實例service-feign上

server:
  port: 8005

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

spring:
  application:
    name: service-zuul

zuul:
  routes:
    api-a:
      path: /ribbon/**
      serviceId: service-ribbon
    api-b:
      path: /feign/**
      serviceId: service-feign

啓動類上添加@EnableZuulProxy開啓zuul服務

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ServiceZuulApplication {

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

}

3、測試
訪問:http://localhost:8005/ribbon/test/hello,可以看到8001和8002在輪詢打印,說明路由已經起了作用

Hello world,this is eureka-client1--8001
Hello world,this is eureka-client1--8002

訪問:http://localhost:8005/feign/test/hello,同樣8001和8002在輪詢打印

Hello world,this is eureka-client1--8001
Hello world,this is eureka-client1--8002

4、服務過濾
這裏可以過濾用戶的請求,並可以對用戶的請求做一些校驗操作,比如Token校驗

/**
 * @author XuJD
 * @create 2019-11-28 15:15
 **/
@Component
public class RouteFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

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

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

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        return null;
    }
filterType:過濾類型,在zuul種提供了4種不同生命週期的過濾類型
			pre:路由之前
			routing:路由之時
			post: 路由之後
			error:發送錯誤調用
filterOrder:過濾順序
shouldFilter:是否需要過濾
run:過濾器的具體邏輯

這時候再訪問:http://localhost:8005/feign/test/hello

token is empty

帶上token則可以正常訪問
http://localhost:8005/ribbon/test/hello?token=123

Hello world,this is eureka-client1--8001
Hello world,this is eureka-client1--8002

源碼地址:https://github.com/xujiangdong/SpringCloud_Study

發佈了233 篇原創文章 · 獲贊 345 · 訪問量 57萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章