Skip to content

Commit

Permalink
服务降级
Browse files Browse the repository at this point in the history
  • Loading branch information
尹吉欢 committed Jan 28, 2019
1 parent 4500bf2 commit 853cc11
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ public class BasicConf {
@Value("${limitRate:10}")
private double limitRate;

@Value("${downGradeServiceStr:default}")
private String downGradeServiceStr;

@ApolloConfig
private Config config;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.context.annotation.Configuration;

import com.cxytiandi.zuul_demo.filter.AuthFilter;
import com.cxytiandi.zuul_demo.filter.DownGradeFilter;
import com.cxytiandi.zuul_demo.filter.LimitFilter;

@Configuration
Expand All @@ -18,4 +19,9 @@ public AuthFilter authFilter() {
public LimitFilter limitFilter() {
return new LimitFilter();
}

@Bean
public DownGradeFilter downGradeFilter() {
return new DownGradeFilter();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.cxytiandi.zuul_demo.filter;


import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.cxytiandi.auth.common.ResponseCode;
import com.cxytiandi.auth.common.ResponseData;
import com.cxytiandi.auth.util.JsonUtils;
import com.cxytiandi.zuul_demo.config.BasicConf;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
* 服务降级过滤器
*
* @author yinjihuan
**/
public class DownGradeFilter extends ZuulFilter {

@Autowired
private BasicConf basicConf;

public DownGradeFilter() {
super();
}

@Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
Object success = ctx.get("isSuccess");
return success == null ? true : Boolean.parseBoolean(success.toString());
}

@Override
public String filterType() {
return "route";
}

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

@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
Object serviceId = ctx.get("serviceId");
if (serviceId != null && basicConf != null) {
List<String> serviceIds = Arrays.asList(basicConf.getDownGradeServiceStr().split(","));
if (serviceIds.contains(serviceId.toString())) {
ctx.setSendZuulResponse(false);
ctx.set("isSuccess", false);
ResponseData data = ResponseData.fail("服务降级中", ResponseCode.DOWNGRADE.getCode());
ctx.setResponseBody(JsonUtils.toJson(data));
ctx.getResponse().setContentType("application/json; charset=utf-8");
return null;
}
}
return null;
}
}

0 comments on commit 853cc11

Please sign in to comment.