5.Zuul网关

一.路由转发

1.依赖


    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    
    
        org.springframework.cloud
        spring-cloud-starter-netflix-zuul
    

2.配置

#zuul
zuul.routes.base.path=/base/**
zuul.routes.base.service-id=base
zuul.routes.qa.path=/qa/**
zuul.routes.qa.service-id=qa
zuul.routes.gathering.path=/gathering/**
zuul.routes.gathering.service-id=gathering

3.启动类
添加注解

@EnableZuulProxy

4.测试
在原来的路径基础上添加微服务名称即可如base,qa
原:
http://localhos:9003/problem/label/1100632156906561536
http://localhost:9101/label/1100632156906561536
改后:
http://localhost/qa/problem/label/1100632156906561536
http://localhost/base/label/1100632156906561536

二.过滤器

@Component
public class ManagerFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() throws ZuulException {
        System.out.println("执行到manager过滤器");
        return null;
    }
}

请求经过网关之后请求头中的信息就没了
RequestContext是次过滤器内的上下文类
currentContext.setSendZuulResponse(false);不知型run方法

@Component
public class ManagerFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() throws ZuulException {
        System.out.println("执行到manager过滤器");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");
        if (!Strings.isNullOrEmpty(token)) {
            currentContext.addZuulRequestHeader("token", token);
        }
        return null;
    }
}

注意:请求头使用Authorization时可能会有问题,最好换用其他字段

你可能感兴趣的:(5.Zuul网关)