1. 程式人生 > 其它 >zuul 閘道器 filter

zuul 閘道器 filter

 

給閘道器做一個攔截

 

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

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 請求攔截
 *
 * @author H
 * @version $id:LoginFilter.java, v 1.0 2022/4/4 15:51:37 $
 */
@Component
public class RequestFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

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

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

    @Override
    public Object run() {
        System.out.println("進入zuul攔截-login攔截");
        //獲取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //獲取Request
        HttpServletRequest request = ctx.getRequest();
        //獲取請求引數
        String token = request.getHeader("head_userName");
        System.out.println("引數token=" + token);

        return null;
    }

}

 

FilterConstants 攔截的型別有幾種

String ERROR_TYPE = "error";
String POST_TYPE = "post";
String PRE_TYPE = "pre";
String ROUTE_TYPE = "route";

 

pre: 在進入請求之前進入這個filter

post: 請求完成之後再進入這個filter