springcloud實戰之12 路由閘道器攔截器
阿新 • • 發佈:2019-01-21
為了能夠在api閘道器中實現對客戶端請求的校驗,我們將繼續介紹spring cloud zuul的另外一個核心功能:請求過濾。zuul允許開發這在api-gateway閘道器上通過定義過濾器來實現對請求的核心攔截與過濾,實現的方法非常簡單。
重構工程(springcloud-server-api-gateway)
新建過濾類
public class AccessFilter extends ZuulFilter {
private final Logger _logger = LoggerFactory.getLogger(this.getClass()) ;
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext() ;
HttpServletRequest request = ctx.getRequest() ;
_logger.info("send {} to {}" ,request.getMethod(),request.getRequestURL().toString());
Object token = request.getParameter("token") ;
if(null == token){
_logger.error("token is null ...");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
}else{
_logger.info("access token is ok!!!" );
}
return null;
}
}
註冊過濾器
@Configuration
public class ApiGatewayConfig {
@Bean
public AccessFilter accessFilter(){
return new AccessFilter();
}
}
呼叫效果圖
呼叫原來的介面,