2018-09-06 10:59:02.0|分类: spring cloud|浏览量: 2503
官方文档: https://github.com/Netflix/zuul/wiki/How-it-Works spring-cloud-starter-netflix-zuul已经依赖引用了spring-cloud-starte-actuator 配置文件management.security.enabled=false server: port: 8888 spring: application: name: zuul eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true management: security: enabled: false 访问routes端口 访问:http://localhost:8888/routes?format=details { 访问filter端点 { Zuul大部分功能都是通过过滤器来实现的。Zuul中定义了四种标准过滤器类型,这些过滤器类型对应于请求的典型生命周期。 (1) PRE:这种过滤器在请求被路由之前调用。我们可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等。 (2) ROUTING:这种过滤器将请求路由到微服务。这种过滤器用于构建发送给微服务的请求,并使用Apache HttpClient或Netfilx Ribbon请求微服务。 (3) POST:这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。 (4) ERROR:在其他阶段发生错误时执行该过滤器。 自定义拦截器 PreRequestLogFilter.java package com.cookqq.zuul; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import javax.servlet.http.HttpServletRequest; public class PreRequestLogFilter extends ZuulFilter { private static final Logger LOGGER = LoggerFactory.getLogger(PreRequestLogFilter.class); public boolean shouldFilter() { // TODO Auto-generated method stub return true; } public Object run() { // TODO Auto-generated method stub RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest httpServletRequest = requestContext.getRequest(); PreRequestLogFilter.LOGGER.info(String.format("send %s request to %s", httpServletRequest.getMethod(), httpServletRequest.getRequestURL().toString())); return null; } @Override public String filterType() { // TODO Auto-generated method stub return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { // TODO Auto-generated method stub return FilterConstants.PRE_DECORATION_FILTER_ORDER-1; } } filterType:返回过滤器的类型。有pre、route、post、error等几种取值,分别对应上文的几种过滤器。详细可以参考com.netflix.zuul.ZuulFilter.filterType() 中的注释。 filterOrder:返回一个int值来指定过滤器的执行顺序,不同的过滤器允许返回相同的数字。 shouldFilter:返回一个boolean值来判断该过滤器是否要执行,true表示执行,false表示不执行。 run:过滤器的具体逻辑。本例中,我们让它打印了请求的HTTP方法以及请求的地址。 ZuulApp.java package com.cookqq.zuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; /** * zuul微服务网关 *https://blog.csdn.net/loongshawn/article/details/50831890 */ @SpringBootApplication @EnableZuulProxy public class ZuulApp { @Bean public PreRequestLogFilter preRequestLogFilter(){ return new PreRequestLogFilter(); } public static void main( String[] args ) { SpringApplication.run(ZuulApp.class, args); } } 启动euraka http://localhost:8761/ 启动provider-user 启动consumer-order 启动zuul http://localhost:8888/consumer-order/user/1请求转换到http://localhost:8080/user/1 |