• Zuul自定义过滤器及熔断配置


    2.2.2.RELEASEspring-cloud-netflix-zuul-2.2.2.RELEASE.jar!orgspringframeworkcloud etflixzuulfilterssupportFilterConstants.class

        public static final String ERROR_TYPE = "error";
        public static final String POST_TYPE = "post";
        public static final String PRE_TYPE = "pre";
        public static final String ROUTE_TYPE = "route";

    Zuul过滤器有四种类型,pre前置和post后置都是相对于routing路由调用远程服务而言的,这三种过滤器不论哪一个出现异常都会到error过滤器,自定义过滤器可以是这四种过滤器之一

    例子为前置过滤器

    package com.company.filter;
    
    import com.netflix.zuul.ZuulFilter;
    import com.netflix.zuul.context.RequestContext;
    import com.netflix.zuul.exception.ZuulException;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.http.HttpServletRequest;
    
    //必须注入sping容器,否则无效
    @Component
    public class LoginFilter extends ZuulFilter{
        @Override
        public String filterType() {
            //指定过滤器类型
            return FilterConstants.PRE_TYPE;
        }
    
        @Override
        public int filterOrder() {
            //指定优先级,越小优先级越高
            return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
        }
    
        @Override
        public boolean shouldFilter() {
            //是否启用过滤
            return true;
        }
    
        @Override
        public Object run() throws ZuulException {
            //过滤逻辑
            //获取Zuul中的request上下文对象
            RequestContext ctx = RequestContext.getCurrentContext();
            //获取request对象
            HttpServletRequest request = ctx.getRequest();
            //简单demo,判断是否带有token参数
            String token = request.getParameter("token");
            if(StringUtils.isBlank(token)){
                //setSendZuulResponse方法传入false表示拦截,默认true放行。
                ctx.setSendZuulResponse(false);
                //响应403状态码
                ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
            }
            return null;
        }
    }

     熔断配置

     Ribbon超时计算公式:(连接时长+读取时长)*(当前实例重试次数+1)*(切换实例重试次数+1)

    zuul:
    retryable: true
    ribbon:
    ConnectTimeout: 250 # 连接超时时间(ms)[默认1秒]
    ReadTimeout: 2000 # 通信超时时间(ms)[默认1秒]
    OkToRetryOnAllOperations: true # 是否对所有操作重试
    MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数[默认是1次]
    MaxAutoRetries: 0 # 同一实例的重试次数[默认是0次]
    hystrix:
    command:
    default:
    execution:
    isolation:
    thread:
    timeoutInMillisecond: 6000 # 熔断超时时长:6000ms[默认是1秒]
  • 相关阅读:
    备忘录 | ‘神器’在手,新世界大门我有
    1001种玩法 | HotswapAgent:支持无限次重定义运行时类与资源
    面面观 | CentOS install etcd 测试
    控制台、终端、虚拟终端和伪终端
    KMP算法,BoyerMoore算法
    qemu kvm 虚拟化
    web端log4net输出错误日志到mysql
    JQuery调用WCF服务,部署在iis
    首篇
    微信支付接口
  • 原文地址:https://www.cnblogs.com/zou-rong/p/12599098.html
Copyright © 2020-2023  润新知