Spring-Cloud-Zuul API Gateway

首先,引入spring-cloud-starter-zuul,還有dependencyManagement中的spring-cloud-dependencies

注意,如果使用的spring-cloud-dependencies是版本Finchley.SR2,結合spring-boot-starter-parent版本2.1.1.RELEASE,會報錯:

The bean 'counterFactory', defined in class path resource [org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration$ZuulCounterFactoryConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration$ZuulMetricsConfiguration.class] and overriding is disabled.

解決辦法:把sprinboot降級到2.0.6.RELEASE即可。以下是全部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>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sc</groupId>
	<artifactId>zuul-gateway</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>zuul-gateway</name>
	<description>Demo project for Spring Boot of Spring Cloud Zuul Gateway</description>

	<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>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-zuul</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Finchley.SR2</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>

</project>

接着,在application.properties定義路由:

spring.application.name=zuul-gateway
server.port=5555
zuul.routes.api-a-url.path=/api-a-url/**
zuul.routes.api-a-url.url=http://localhost:8081/

那麼,當我們訪問http://localhost:5555/api-a-url/hello, API網關服務會講請求路由到http://localhost:8081/hello. 如圖:

特別的,Spring-Cloud-Zuul默認引入spring-cloud-actuator, 所以在啓動的時候可以看到日誌:

但是,這種基於傳統路由的配置方式對於運維非常不友好,所以,必須實現面向服務的路由!

首先,引入spring-clould-eureka:

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>

定義serviceId和path:

spring.application.name=zuul-gateway
server.port=5555
#zuul.routes.api-a-url.path=/api-a-url/**
#zuul.routes.api-a-url.url=http://localhost:8081/
zuul.routes.api-a.path=/api-a/**
zuul.routes.api-a.serviceId=hello-service
zuul.routes.api-b.path=/api-b/**
zuul.routes.api-b.serviceId=feign-consumer
eureka.client.service-url.defaultZone=http://localhost:12451/eureka/,http://localhost:12452/eureka/

那麼,訪問curl http://127.0.0.1:5555/api-a/hello/等同於訪問curl http://127.0.0.1:8081/hello/或者curl http://127.0.0.1:8082/hello/

訪問curl http://127.0.0.1:5555/api-b/feign-consumer3/等同於訪問curl http://127.0.0.1:9001/feign-consumer3/

如圖:

在eureka面板可以看到服務zuul-gateway

接着,我們思考假設需要在url必須附帶一個accessToken才實現轉發,也就是增加一個全局filter,

那麼新定義一個AccessFilter繼承com.netflix.zuul.ZuulFilter:

注意,

  • 裏面的方法filterType返回pre表示前置,
  • filterOrder返回0表示順序,
  • shouldFilter返回true表示應該執行filter
  • run表示具體執行filter,主要是對com.netflix.zuul.context.RequestContext中的HttpServletRequest進行賦值
package com.sc.zuulgateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class AccessFilter  extends ZuulFilter{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @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();
        this.logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
        Object accessToken = request.getParameter("accessToken");
        if (accessToken == null){
            this.logger.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }
        this.logger.info("access token ok");
        return null;
    }
}

然後,創建具體的Bean啓動過濾器:

package com.sc.zuulgateway;

import com.sc.zuulgateway.filter.AccessFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableZuulProxy
public class ZuulGatewayApplication {

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

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

}

結果:當url不附帶accessToken的時候返回http statusCode爲401,並且Content-Length爲0.

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