Spring Cloud Netflix 使用路由网关的服务过过滤功能(三)
创建服务过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package com.xzt.zuul;
import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest; import java.io.IOException;
@Component public class MyFilter extends ZuulFilter { private Logger logger = LoggerFactory.getLogger(MyFilter.class);
@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 context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); logger.info("{} >>> {}", request.getMethod(), request.getRequestURL().toString()); String message = request.getParameter("message"); if (message == null) { logger.warn("Message is empty"); context.setSendZuulResponse(false); context.setResponseStatusCode(401); try { context.getResponse().getWriter().write("Message is empty"); } catch (IOException e) { } } else { logger.info("OK"); } return null; } }
|
测试
浏览器访问:http://localhost:8769/api/a/hi?message=HelloZuul
网页显示