<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-zuul-adapter</artifactId> <version>1.6.0</version> </dependency>
@Configuration public class ZuulConfig { @Bean public ZuulFilter sentinelZuulPreFilter() { return new SentinelZuulPreFilter(); } @Bean public ZuulFilter sentinelZuulPostFilter() { return new SentinelZuulPostFilter(); } @Bean public ZuulFilter sentinelZuulErrorFilter() { return new SentinelZuulErrorFilter(); } @PostConstruct public void doInit() { // 註冊 FallbackProvider ZuulBlockFallbackManager.registerProvider(new MyBlockFallbackProvider()); initGatewayRules(); } /** * 配置限流規則 */ private void initGatewayRules() { Set<GatewayFlowRule> rules = new HashSet<>(); rules.add(new GatewayFlowRule("yinjihuan").setCount(1) // 限流閾值 .setIntervalSec(1) // 統計時間窗口,單位是秒,默認是 1 秒 ); GatewayRuleManager.loadRules(rules); } }
zuul.routes.yinjihuan.path=/cxytiandi/** zuul.routes.yinjihuan.url=http://cxytiandi.com
若是想修改提示內容能夠本身實現ZuulBlockFallbackProvider接口,框架默認提供的實現是DefaultBlockFallbackProvider,源碼以下:json
public class DefaultBlockFallbackProvider implements ZuulBlockFallbackProvider { @Override public String getRoute() { return "*"; } @Override public BlockResponse fallbackResponse(String route, Throwable cause) { if (cause instanceof BlockException) { return new BlockResponse(429, "Sentinel block exception", route); } else { return new BlockResponse(500, "System Error", route); } } }
用法其實跟Zuul中的FallbackProvider一致,可是FallbackProvider比較好的是返回的ClientHttpResponse,咱們能夠自定義響應內容。api
Sentinel提供的ZuulBlockFallbackProvider接口中定義的返回對象是BlockResponse ,也就意味着限制了響應的字段,BlockResponse中有code,message,route三個字段,若是我想返回status, msg這兩個字段目前我沒找到其它的方式,不知道後續會不會支持,其實最好的是也返回ClientHttpResponse,這樣就能夠自定義響應內容了。app
這邊有個小插曲,就是咱們自定義fallbackResponse的時候若是用中文message的話,響應內容是亂碼,以下:框架
{ code: 429, message: "??????", route: "yinjihuan" }
我看了下SentinelZuulPreFilter中的代碼,以下:
這邊是構造了BlockResponse,而後設置到ResponseBody中,可是沒有進行編碼設置,我本身改了下源碼,加了一行代碼:ide
ctx.getResponse().setContentType("application/json; charset=utf-8");
加了上面的代碼後,中文就不會亂碼了,效果以下:post
{ code: 429, message: "訪問太頻繁啦", route: "yinjihuan" }