首先,引入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.