Zuul的应用

一、介绍

  

 

 注:Zuul中默认就已经集成了Ribbon负载均衡和Hystix熔断机制。但是所有的超时策略都是走的默认值,比如熔断超时时间只有1S,很容易就触发了。

 二、依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-netflix-zuul</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

三、配置 

单一配置:
zuul:
prefix: /api #前缀
retryable: true routes: user-service: # 这里是路由id,随意写 path: /user-service/** # 这里是映射路径 url: http://127.0.0.1:8081 # 映射路径对应的实际url地址
 
动态路由:
zuul: routes: user-service: # 这里是路由id,随意写 path: /user-service/** # 这里是映射路径 serviceId: user-service # 指定服务名称
 
简化配置:
zuul: routes: user-service: /user-service/** # 这里是映射路径
 
综合配置:
zuul: retryable: true ribbon: ConnectTimeout: 250 # 连接超时时间(ms) ReadTimeout: 2000 # 通信超时时间(ms) OkToRetryOnAllOperations: true # 是否对所有操作重试 MaxAutoRetriesNextServer: 2 # 同一服务不同实例的重试次数 MaxAutoRetries: 1 # 同一实例的重试次数 hystrix: command: default: execution: isolation: thread: timeoutInMillisecond: 6000 # 熔断超时时长:6000ms

 四、过滤器

参考:https://blog.csdn.net/wo18237095579/article/details/83543592

@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class AuthFilter extends ZuulFilter{

@Autowired
private JwtProperties prop;
@Autowired
private FilterProperties filterProp;

@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}

@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
}

@Override
public boolean shouldFilter() {
RequestContext ctx=RequestContext.getCurrentContext();
HttpServletRequest request=ctx.getRequest();
String path=request.getRequestURI();
boolean isAllowPath=isAllowPath(path);
return !isAllowPath;
}

public boolean isAllowPath(String path){
for(String allowPath:filterProp.getAllowPaths()){
if(path.startsWith(allowPath)) {
return true;
}
}
return false;
}

@Override
public Object run() throws ZuulException {
RequestContext ctx=RequestContext.getCurrentContext();
HttpServletRequest request=ctx.getRequest();
String token= CookieUtils.getCookieValue(request,prop.getCookieName());

try {
UserInfo user= JwtUtils.getUserInfo(prop.getPublicKey(),token);
} catch (Exception e) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(403);
}
return null;
}
}
posted @ 2020-05-04 17:07  Water540  阅读(194)  评论(0编辑  收藏  举报