SpringCloud Zuul 過濾器
阿新 • • 發佈:2019-01-02
今天主要介紹的是前置攔截器(Pre)和後置攔截器(Post)
1.Pre主要實現的是所有的請求中都必須含有token引數,如果沒有就不讓通過,程式碼如下
package com.lfv.product.filter; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import io.micrometer.core.instrument.util.StringUtils; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; import javax.servlet.http.HttpServletRequest; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER; /** * PRE Filter 前置過濾器 * @author lf * */ @Component public class TokenFilter extends ZuulFilter { @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return PRE_DECORATION_FILTER_ORDER - 1; } @Override public String filterType() { return PRE_TYPE; } @Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); String tocken = request.getParameter("tocken"); if(StringUtils.isNotBlank(tocken)) { System.out.println("tocken="+tocken); }else { requestContext.setSendZuulResponse(false);//驗證不不通過 requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());//返回401 許可權不足 } return null; } }
無tocken的訪問,返回401許可權沒有通過
有token的訪問
2.Post 後置攔截器程式碼如下
package com.lfv.product.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_RESPONSE_FILTER_ORDER; import java.util.Date; import javax.servlet.http.HttpServletResponse; /** * Post後置過濾器,向返回值正新增資料 * @author lf * */ @Component public class AddResponseHeaderFilter extends ZuulFilter { @Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletResponse response = requestContext.getResponse(); response.setHeader("Zuul Post Filter response", (new Date())+""); return null; } @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return SEND_RESPONSE_FILTER_ORDER - 1; } @Override public String filterType() { return POST_TYPE; } }
返回的結果如下圖