Zuul网关

网关是什么就不用多说了,网关最大的作用就是隐藏我们内部服务器的IP地址,外界通过网管访问,由网管决定请求是否可以进入内部服务,因此网管也可以做权限检验,网关还具备动态路由,负载均衡等功能。

搭建zuul模块

pom文件

<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>

启动类上加上@EnableZuulProxy开启网关

@SpringBootApplication
@EnableZuulProxy
public class ZuulDemoApplication {

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

application.yml

server:
  port: 8087
spring:
  application:
    name: zuul-demo
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/,http://localhost:8082/eureka/
zuul:
  routes:
    #可以任意,一般都会和服务名相同
    eureka-client:
      #访问路径
      path: /eureka-client/**
      #会映射到这个服务上
      serviceId: eureka-client
	#也可以直接映射到某个ip,一般不会这么做
	  #url: http://localhost:8080

接着我们启动网关,通过网关去访问eureka客户端
在这里插入图片描述
在这里插入图片描述
我们可以看出网关具备负载均衡的功能。

接下来我们测试一下Zuul的过滤器功能

public class IdFilter extends ZuulFilter {
	//决定过滤器类型
    @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 requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //这里校验的是如果id为空,就不通过
        String id = request.getParameter("id");
        if (id == null){
        	//设置网关不通过
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("id is null");
        }
        //通过id访问数据库之类的操作
        return null;
    }
}

在启动类上配置过滤器

@Bean
public IdFilter idFilter(){
    return new IdFilter();
}

接下来我们启动程序,我们发现没有传id属性的时候,zuul网关会拦截请求

在这里插入图片描述

带上id后,就可以正常访问

在这里插入图片描述

filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:
  1.pre:可以在请求被路由之前调用,用在路由映射的阶段是寻找路由映射表的
  2.route:在路由请求时候被调用,具体的路由转发过滤器是在routing路由器具体的请求转发的时候会调用
  3.error:处理请求时发生错误时被调用
  4.post:当routing,error运行完后才会调用该过滤器,是在最后阶段的

最后说几个zuul的配置参数:
zuul.ignored-services 忽略的服务
zuul.ignored-patterns 忽略的路径
zuul.prefix= /api/**
配置前缀 可以看到那么你访问的服务都必须要加/api/前缀,例如/api/hello-service/**
zuul.sensitive-headers=: cookie 设置不禁用的请求头,cookie默认是禁用的

//禁用过滤器
zuul.IdFilter.pre.disable=true; 禁用这个过滤器
IdFilter:是类名
pre:是过滤器类型

猜你喜欢

转载自blog.csdn.net/ROAOR1/article/details/88297079