服务网关是微服务架构中一个不可或缺的部分。通过服务网关统一向外系统提供REST API的过程中,除了具备服务路由、均衡负载功能之外,它还具备了权限控制
等功能。Spring Cloud Netflix中的Zuul就担任了这样的一个角色,为微服务架构提供了前门保护的作用,同时将权限控制这些较重的非业务逻辑内容迁移到服务路由层面,使得服务集群主体能够具备更高的可复用性和可测试性。
创建一个新项目:
引入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
开启zuul
开启eureka
@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class GetewayApplication {
public static void main(String[] args) {
SpringApplication.run(GetewayApplication.class, args);
}
}
yml配置文件
方式1:
server:
port: 10010
spring:
application:
name: api-gateway #指定服务名
zuul:
routes:
test: # 这里是路由id,随意写
path: /server/** # 这里是映射路径
url: 127.0.0.1/8081 # 映射路径对应的实际url地址
访问路径(localhost:10010/server/ 被映射到了http://localhost:8081)
http://localhost:10010/server/customer/
方式二:
zuul:
routes:
test: # 这里是路由id,随意写
path: /server/** # 这里是映射路径
url: customer # 映射路径对应的实际url地址
方式三:
zuul:
routes:
customer: /server/** # 这里是服务名称 不能乱写 不能乱写 不能乱写
还可以添加路由前缀:
zuul:
prefix: /api # 添加路由前缀
routes:
customer: /server/** # 这里是服务名称 不能乱写
访问路径为:http://localhost:10010/api/server/customer/
过滤器
Zuul作为网关的其中一个重要功能,就是实现请求的鉴权。而这个动作我们往往是通过Zuul提供的过滤器来实现的。
public abstract ZuulFilter implements IZuulFilter{
abstract public String filterType();
abstract public int filterOrder();
boolean shouldFilter();// 来自IZuulFilter
Object run() throws ZuulException;// IZuulFilter
}
shouldFilter
:返回一个Boolean
值,判断该过滤器是否需要执行。返回true执行,返回false不执行。run
:过滤器的具体业务逻辑。filterType
:返回字符串,代表过滤器的类型。包含以下4种:pre
:请求在被路由之前执行routing
:在路由请求时调用post
:在routing和errror过滤器之后调用error
:处理请求时发生错误调用
filterOrder
:通过返回的int值来定义过滤器的执行顺序,数字越小优先级越高。
负载均衡和熔断
Zuul中默认就已经集成了Ribbon负载均衡和Hystix熔断机制。但是所有的超时策略都是走的默认值,比如熔断超时时间只有1S,很容易就触发了。因此建议我们手动进行
配置:
zuul:
retryable: true
ribbon:
ConnectTimeout: 250 # 连接超时时间(ms)
ReadTimeout: 2000 # 通信超时时间(ms)
OkToRetryOnAllOperations: true # 是否对所有操作重试
MaxAutoRetriesNextServer: 2 # 同一服务不同实例的重试次数
MaxAutoRetries: 1 # 同一实例的重试次数
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMillisecond: 6000 # 熔断超时时长:6000ms