springCloud笔记系列(4)-网关配置Zuul

1.SpringCloudZuul是基于Netflix Zuul实现的API网关组件,它实现了请求路由、负载均衡、校验过滤、与服务治理框架的结合、请求转发是的熔断机制和服务的聚合等功能web

2.引入依赖spring

<dependencies>api

<dependency>架构

<groupId>org.springframework.boot</groupId>app

<artifactId>spring-boot-starter-web</artifactId>负载均衡

</dependency>框架

<dependency>spring-boot

<groupId>org.springframework.cloud</groupId>post

<artifactId>spring-cloud-starter-zuul</artifactId>url

<version>1.3.4.RELEASE</version>

</dependency>

 

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka</artifactId>

<version>1.3.2.RELEASE</version>

</dependency>

</dependencies>

3.在主类上使用@EnableZuulProxy注解开启API网关服务功能

@SpringBootApplication

//开启网关路由

@EnableZuulProxy

@EnableEurekaClient

public class SpringzuulApplication {

 

public static void main(String[] args) {

SpringApplication.run(SpringzuulApplication.class, args);

}

}

4.再配置文件上面配置一些路由信息

spring:

application:

name: zuul-client

server:

port: 8001

zuul:

routes:

# 面向服务的路由

api-a:

path: /api-a/**

serviceId: one-client

# 传统的路由

api-b-url:

path: /api-b-url/**

url: http://localhost:8011/

eureka:

client:

service-url:

defaultZone: http://localhost:8000/eureka/

主要的配置解析:本配置配置了两种的策略使用两种路由规则的配置方法,一种是面向服务的,一种是使用传统的url。全部符合/api-a/**的请求都将转发到one-client,一样全部符合/api-b-url/**的请求都将转发到http://localhost:8011/,也是one-client的地址。两种规则的配置很明显:面向服务的使用serviceId配置服务实例,而传统的直接使用服务的地址。

其余配置

zuul.ignored-services=hello-service:忽略掉一个服务;

zuul.ignored-patterns=/**/feign/**: 忽略/feign接口路由;

zuul.prefix:为路由添加统一前缀;

zuul.add-host-header: true:在请求路由转发前为请求设置Host头信息;

zuul.sensitiveHeaders=:设置全局参数为空来覆盖默认敏感头信息

zuul.routes.<route>.customSensitiveHeaders=true:对指定路由开启自定义敏感头

zuul.routes.<route>.sentiviteHeaders=:将指定路由的敏感头设置为空。

zuul.retryable=false:关闭重试机制

zuul.routes.<route>.retryable=false:指定路由关闭重试机制

zuul.<SimpleClassName>.<fileterType>.disable=true:禁用指定的过滤器,<SimpleClassName>表明过滤器的类名,<fileterType>表明过滤器的类型。

在Zuul中Hystrix和Ribbon的配置与传统的Hystrix和Ribbon服务的配置同样。

4.请求的结果

5.数据的过滤

在单体架构的时候咱们一般会使用拦截器或过滤器对请求进行权限的校验,一样在SpringCloudZuul中也提供了过滤器来进行请求的过滤与拦截,实现方法只要咱们继承抽象类ZuulFilter并实现它定义的4个抽象方法

@Component

public class AccessFilter extends ZuulFilter {

1. filterType:过滤器类型,他决定过滤器在请求的哪一个生命周期执行。在Zuul中有四种不一样的生命周期过滤器

pre:能够在请求被路由以前调用;

routing:在路由请求是调用;

post:在routing和error过滤器以后被调用;

error:处理请求是发生错误是被调用

2. filterOrder:过滤器的执行顺序,数值越小优先级越高

3. shouldFilter:判断过滤器是否须要执行

4. run: 过滤器的具体逻辑。上面的run方法中判断请求是否带有accessToken参数,若是没有则是非法请求,使用 currentContext.setSendZuulResponse(false);表示该请求不进行路由。而后设置响应码。

相关文章
相关标签/搜索