微服务之路由网关(zuul)

"Hello SpringBoot, Hello SpringClould"

Posted by 墨城烟柳(Mcyl) on January 9, 2019

“Hello everyone! ”

路由网关(zuul)简介

路由网关(zuul)由来:

Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/a转发到到a服务,/api/b转发到到b服务。zuul默认和Ribbon结合实现了负载均衡的功能。

zuul有以下功能:

1
2
3
4
5
6
7
8
9
10
Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
Load Shedding
Security
Static Response handling
Active/Active traffic management

第一步:创建条件

这一篇文章基于上一篇文章的工程.

第二步:创建service-zuul工程:

右键工程->创建创建module->选择spring initialir->web->web,cloud discovery->eureka discovery,cloud routing->zuul,然后一直下一步就行了。

创建完成后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?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.1.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.test</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>Greenwich.RC2</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-starter-test</artifactId>
			<scope>test</scope>
		</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>

配置appication.yml文件:

以/api-a/开头的请求都转发给service-ribbon服务;以/api-b/开头的请求都转发给service-feign服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server:
  port: 9875
eureka:
  client:
	service-url:
	  defaultZone: http://localhost:9871/eureka/
spring:
  application:
	name: service-zuul
zuul:
  routes:
	api-a:
	  paht: /api-a/**
	  serviceId: service-ribbon
	api-b:
	  path: /api-b/**
	  serviceId: service-feign

第三步 配置启动类

在工程的启动类中添加@EnableZuulProxy,开启zuul的功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

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

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

}

第四步:启动所有工程

打开 http://localhost:9875/api-a/hello/?name=handsomeman ,你会在浏览器上看到显示:

hello handsomeman ,i am from port:9872

打开 http://localhost:9875/api-b/hello/?name=handsomeman ,浏览器会显示:

hello handsomeman ,i am from port:9872

第五步:实现服务过滤

zuul不仅只是路由,并且还能过滤,做一些安全验证。继续改造工程,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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 org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

	private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);

	// 返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型
	@Override
	public String filterType() {
//        1.pre:可以在请求被路由之前调用
//        2.routing:在请求时被调用
//        3.post:在routing和error过滤之后调用。
//        4.error:处理请求时发生错误是被调用。
		return "pre";
	}

	// 过滤的顺序
	@Override
	public int filterOrder() {
		return 0;
	}

	// 这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
	@Override
	public boolean shouldFilter() {
		return true;
	}

	// 过滤器的具体逻辑。可以很复杂,包括查sql,nosql去判断该请求到底有没有权限访问
	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		logger.info(String.format("请求方式:%s -----请求url: %s", request.getMethod(), request.getRequestURL().toString()));
		Object accessToken = request.getParameter("token");
		if(accessToken == null) {
			logger.warn("token is empty");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			try {
				ctx.getResponse().getWriter().write("token is empty");
			}catch (Exception e){

			}
			return null;
		}
		logger.info("ok");
		return null;
	}
}

第六步:启动所有工程

打开 http://localhost:9875/api-a/hello/?name=handsomeman ,你会在浏览器上看到显示:

token is empty

打开 http://localhost:9875/api-a/hello/?token=123&name=handsomeman ,浏览器会显示:

hello handsomeman ,i am from port:9872

源码下载:

https://github.com/mochengyanliu/SpringCloudLearn/tree/master/section5