zuul过滤器

一 新建项目microservice-gateway-zuul-filter
二 编写自定义Zuul过滤器
package com.itmuch.cloud.study.filters.pre;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class PreRequestLogFilter extends ZuulFilter {
  private static final Logger LOGGER = LoggerFactory.getLogger(PreRequestLogFilter.class);

  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 1;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    PreRequestLogFilter.LOGGER.info(String.format("send %s request to %s", request.getMethod(), request.getRequestURL().toString()));
    return null;
  }
}
由代码可知,自定义的Zuul Filter需要实现以下几个方法。
filterType:返回过滤器的类型。有pre、route、post、error等几种取值,分布对应上文的几种过滤器。
filterOrder:返回一个int值来指定过滤器的执行顺序,不同的过滤器允许返回相同的数字。
shouldFilter:返回一个boolean值来判断该过滤器是否要执行,true表示执行,false表示不执行。
run:过滤器的具体逻辑。本例中让它打印了请求的HTTP方法以及请求的地址。
三 编写启动类
package com.itmuch.cloud.study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

import com.itmuch.cloud.study.filters.pre.PreRequestLogFilter;

@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
  public static void main(String[] args) {
    SpringApplication.run(ZuulApplication.class, args);
  }

  @Bean
  public PreRequestLogFilter preRequestLogFilter() {
    return new PreRequestLogFilter();
  }
}
四 测试
1 启动eureka
2 启动user微服务
3 启动zuul-filter
[nio-8040-exec-4] c.i.c.s.filters.pre.PreRequestLogFilter  : send GET request to http://localhost:8040/microservice-provider-user/1
五 禁用Zuul过滤器
Spring Cloud默认为Zuul编写并启动了一些过滤器,例如:DebugFilter、FromBodyWrapperFilter、PreDecorationFilter等。这些过滤器都存放在spring-cloud-netflix-core这个jar包的 springframework.cloud.netflix.zuul.filters包中。
一些场景下,想要禁用部分过滤器,该怎么办?
只需设置zuul.<SimpleClassName>.<filterType>.disable=true,即可禁用SimpleClassName所对应的过滤器。以过滤器 org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter为例,只须设置zuul.SendResponseFilter.post.disable=true,即可禁用该过滤器。
同理,如果想禁用本例编写的过滤器,只需要设置zuul.PreRequestLogFilter.pre.disable=true即可。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/80833404