Eureka(F 版本)教程五 路由网关 (zuul)
Load Shedding
Security
Static Response handling
Active/Active traffic management
二、准备工作
继续使用上一节的工程。在原有的工程上,创建一个新的工程。
三、创建 service-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 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 起到了路由的作用
四、服务过滤
zuul 不仅只是路由,并且还能过滤,做一些安全验证。继续改造工程;
@Component
public class MyFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogg
er(MyFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
评论