Spring Cloud Zuul 网关服务以及核心过滤器(Dalston版)

服务网关搭建 

服务网关是微服务架构中一个不可或缺的部分。通过服务网关统一向外系统提供REST API的过程中,除了具备服务路由、均衡负载功能之外,它还具备了权限控制等功能。Spring Cloud Netflix中的Zuul就担任了这样的一个角色,为微服务架构提供了前门保护的作用,同时将权限控制这些较重的非业务逻辑内容迁移到服务路由层面,使得服务集群主体能够具备更高的可复用性和可测试性。

创建一个基础的Spring Boot工程,并在pom.xml中引入需要的依赖内容:

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.8.RELEASE
        
    

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

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Dalston.SR2
                pom
                import
            
        
    

在应用主类中通过@EnableZuulProxy注解开启Zuul

@EnableZuulProxy
@SpringCloudApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

 这里使用@SpringCloudApplication注解,它整合了@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreaker

在配置文件加入服务名、端口号、注册中心地址、路由配置

spring.application.name=gateway-server
server.port=1100
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/

zuul.routes.user-server=/user/**

启动user-server服务、网关服务,访问http://localhost:1100/user/xx?zz=hh即可转发到user服务对应的接口

 

自定义过滤器

在服务网关中定义过滤器只需要继承ZuulFilter抽象类实现其定义的四个抽象函数就可对请求进行拦截与过滤。

定义一个TestFilter拦截用户ID不等于1的用户

@Component
public class TestFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String userId = request.getParameter("userId");
        if(Long.valueOf(userId) != 1) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.setResponseBody("failed!");
            return null;
        }
        return null;
    }
}
  • filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:
    • pre:可以在请求被路由之前调用
    • routing:在路由请求时候被调用
    • post:在routing和error过滤器之后被调用
    • error:处理请求时发生错误时被调用
  • filterOrder:通过int值来定义过滤器的执行顺序
  • shouldFilter:返回一个boolean类型来判断该过滤器是否要执行,所以通过此函数可实现过滤器的开关。在上例中,我们直接返回true,所以该过滤器总是生效。
  • run:过滤器的具体逻辑。需要注意,这里我们通过ctx.setSendZuulResponse(false)令zuul过滤该请求,不对其进行路由,然后通过ctx.setResponseStatusCode(401)设置了其返回的错误码,通过ctx.setResponseBody(body)对返回body内容进行编辑等。 

 

全局异常处理

由于在请求生命周期的preroutepost三个阶段中有异常抛出的时候都会进入error阶段的处理,所以我们可以通过创建一个error类型的过滤器来捕获这些异常信息,并根据这些异常信息在请求上下文中注入需要返回给客户端的错误描述。

Dalston之后的版本已经自带全局异常处理。

@Component
public class ErrorFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        Throwable throwable = context.getThrowable();
        System.out.println("错误"+throwable.getCause().getMessage());
        context.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        context.set("error.exception", throwable.getCause());
        return null;
    }
}

 

你可能感兴趣的:(Spring,Cloud,网关服务,zuul,filter,Spring,Cloud)