概述
Zuul 不仅仅只是路由,还有很多强大的功能,本节演示一下它的服务过滤功能,比如用在安全验证方面。
创建服务过滤器
继承 ZuulFilter 类并在类上增加 @Component 注解就可以使用服务过滤功能了,非常简单方便
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 72 73 74 75 76 77 78 79 80 81 82 package com.funtl.hello.spring.cloud.zuul.filter;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 LoginFilter extends ZuulFilter { private static final Logger logger = LoggerFactory.getLogger(LoginFilter.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 token = request.getParameter("token" ); if (token == null ) { logger.warn("Token is empty" ); context.setSendZuulResponse(false ); context.setResponseStatusCode(401 ); try { context.getResponse().getWriter().write("Token is empty" ); } catch (IOException e) { } } else { logger.info("OK" ); } return null ; } }
filterType
返回一个字符串代表过滤器的类型,在 Zuul 中定义了四种不同生命周期的过滤器类型
pre:路由之前
routing:路由之时
post: 路由之后
error:发送错误调用
filterOrder
过滤的顺序
shouldFilter
是否需要过滤,这里是 true,需要过滤
run
过滤器的具体业务代码
测试过滤器
浏览器访问:http://localhost:8769/api/a/hi?message=HelloZuul ,网页显示
浏览器访问:http://localhost:8769/api/b/hi?message=HelloZuul&token=123 ,网页显示
1 Hi,your message is :"HelloZuul" i am from port:8763
案例源码:https://github.com/V-Vincen/hello-spring-cloud
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !