电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

spring cloud gateway集成hystrix實戰篇

瀏覽:4日期:2023-07-01 11:53:11
spring cloud gateway集成hystrix

本文主要研究一下spring cloud gateway如何集成hystrix

maven

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>

添加spring-cloud-starter-netflix-hystrix依賴,開啟hystrix

配置實例

hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000spring: cloud: gateway: discovery:locator: enabled: true routes: - id: employee-serviceuri: lb://employee-servicepredicates:- Path=/employee/**filters:- RewritePath=/employee/(?<path>.*), /${path}- name: Hystrix args: name: fallbackcmd fallbackUri: forward:/fallback 首先filter里頭配置了name為Hystrix的filter,實際是對應HystrixGatewayFilterFactory 然后指定了hystrix command的名稱,及fallbackUri,注意fallbackUri要以forward開頭 最后通過hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds指定該command的超時時間fallback實例

@RestController@RequestMapping('/fallback')public class FallbackController { @RequestMapping('') public String fallback(){return 'error'; }}源碼解析

GatewayAutoConfiguration

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java

@Configuration@ConditionalOnProperty(name = 'spring.cloud.gateway.enabled', matchIfMissing = true)@EnableConfigurationProperties@AutoConfigureBefore(HttpHandlerAutoConfiguration.class)@AutoConfigureAfter({GatewayLoadBalancerClientAutoConfiguration.class, GatewayClassPathWarningAutoConfiguration.class})@ConditionalOnClass(DispatcherHandler.class)public class GatewayAutoConfiguration { //...... @Configuration @ConditionalOnClass({HystrixObservableCommand.class, RxReactiveStreams.class}) protected static class HystrixConfiguration {@Beanpublic HystrixGatewayFilterFactory hystrixGatewayFilterFactory(DispatcherHandler dispatcherHandler) { return new HystrixGatewayFilterFactory(dispatcherHandler);} } //......}

引入spring-cloud-starter-netflix-hystrix類庫,就有HystrixObservableCommand.class, RxReactiveStreams.class,便開啟HystrixConfiguration

HystrixGatewayFilterFactory

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/HystrixGatewayFilterFactory.java

/** * Depends on `spring-cloud-starter-netflix-hystrix`, {@see http://cloud.spring.io/spring-cloud-netflix/} * @author Spencer Gibb */public class HystrixGatewayFilterFactory extends AbstractGatewayFilterFactory<HystrixGatewayFilterFactory.Config> { public static final String FALLBACK_URI = 'fallbackUri'; private final DispatcherHandler dispatcherHandler; public HystrixGatewayFilterFactory(DispatcherHandler dispatcherHandler) {super(Config.class);this.dispatcherHandler = dispatcherHandler; } @Override public List<String> shortcutFieldOrder() {return Arrays.asList(NAME_KEY); } public GatewayFilter apply(String routeId, Consumer<Config> consumer) {Config config = newConfig();consumer.accept(config);if (StringUtils.isEmpty(config.getName()) && !StringUtils.isEmpty(routeId)) { config.setName(routeId);}return apply(config); } @Override public GatewayFilter apply(Config config) {//TODO: if no name is supplied, generate one from command id (useful for default filter)if (config.setter == null) { Assert.notNull(config.name, 'A name must be supplied for the Hystrix Command Key'); HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(getClass().getSimpleName()); HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(config.name); config.setter = Setter.withGroupKey(groupKey) .andCommandKey(commandKey);}return (exchange, chain) -> { RouteHystrixCommand command = new RouteHystrixCommand(config.setter, config.fallbackUri, exchange, chain); return Mono.create(s -> {Subscription sub = command.toObservable().subscribe(s::success, s::error, s::success);s.onCancel(sub::unsubscribe); }).onErrorResume((Function<Throwable, Mono<Void>>) throwable -> {if (throwable instanceof HystrixRuntimeException) { HystrixRuntimeException e = (HystrixRuntimeException) throwable; if (e.getFailureType() == TIMEOUT) { //TODO: optionally set statussetResponseStatus(exchange, HttpStatus.GATEWAY_TIMEOUT);return exchange.getResponse().setComplete(); }}return Mono.error(throwable); }).then();}; } //......}

這里創建了RouteHystrixCommand,將其轉換為Mono,然后在onErrorResume的時候判斷如果HystrixRuntimeException的failureType是FailureType.TIMEOUT類型的話,則返回GATEWAY_TIMEOUT(504, 'Gateway Timeout')狀態碼。

RouteHystrixCommand

//TODO: replace with HystrixMonoCommand that we write private class RouteHystrixCommand extends HystrixObservableCommand<Void> {private final URI fallbackUri;private final ServerWebExchange exchange;private final GatewayFilterChain chain;RouteHystrixCommand(Setter setter, URI fallbackUri, ServerWebExchange exchange, GatewayFilterChain chain) { super(setter); this.fallbackUri = fallbackUri; this.exchange = exchange; this.chain = chain;}@Overrideprotected Observable<Void> construct() { return RxReactiveStreams.toObservable(this.chain.filter(exchange));}@Overrideprotected Observable<Void> resumeWithFallback() { if (this.fallbackUri == null) {return super.resumeWithFallback(); } //TODO: copied from RouteToRequestUrlFilter URI uri = exchange.getRequest().getURI(); //TODO: assume always? boolean encoded = containsEncodedParts(uri); URI requestUrl = UriComponentsBuilder.fromUri(uri) .host(null) .port(null) .uri(this.fallbackUri) .build(encoded) .toUri(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl); ServerHttpRequest request = this.exchange.getRequest().mutate().uri(requestUrl).build(); ServerWebExchange mutated = exchange.mutate().request(request).build(); return RxReactiveStreams.toObservable(HystrixGatewayFilterFactory.this.dispatcherHandler.handle(mutated));} } 這里重寫了construct方法,RxReactiveStreams.toObservable(this.chain.filter(exchange)),將reactor的Mono轉換為rxjava的Observable 這里重寫了resumeWithFallback方法,針對有fallbackUri的情況,重新路由到fallbackUri的地址Config

public static class Config {private String name;private Setter setter;private URI fallbackUri;public String getName() { return name;}public Config setName(String name) { this.name = name; return this;}public Config setFallbackUri(String fallbackUri) { if (fallbackUri != null) {setFallbackUri(URI.create(fallbackUri)); } return this;}public URI getFallbackUri() { return fallbackUri;}public void setFallbackUri(URI fallbackUri) { if (fallbackUri != null && !'forward'.equals(fallbackUri.getScheme())) {throw new IllegalArgumentException('Hystrix Filter currently only supports ’forward’ URIs, found ' + fallbackUri); } this.fallbackUri = fallbackUri;}public Config setSetter(Setter setter) { this.setter = setter; return this;} }

可以看到Config校驗了fallbackUri,如果不為null,則必須以forward開頭

小結

spring cloud gateway集成hystrix,分為如下幾步:

添加spring-cloud-starter-netflix-hystrix依賴 在對應route的filter添加name為Hystrix的filter,同時指定hystrix command的名稱,及其fallbackUri(可選) 指定該hystrix command的超時時間等。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 电磁流量计厂家_涡街流量计厂家_热式气体流量计-青天伟业仪器仪表有限公司 | 啤酒设备-小型啤酒设备-啤酒厂设备-济南中酿机械设备有限公司 | 体视显微镜_荧光生物显微镜_显微镜报价-微仪光电生命科学显微镜有限公司 | 噪声治理公司-噪音治理专业隔音降噪公司 | 胶泥瓷砖胶,轻质粉刷石膏,嵌缝石膏厂家,腻子粉批发,永康家德兴,永康市家德兴建材厂 | 压砖机_电动螺旋压力机_粉末成型压力机_郑州华隆机械tel_0371-60121717 | DAIKIN电磁阀-意大利ATOS电磁阀-上海乾拓贸易有限公司 | 东莞螺杆空压机_永磁变频空压机_节能空压机_空压机工厂批发_深圳螺杆空压机_广州螺杆空压机_东莞空压机_空压机批发_东莞空压机工厂批发_东莞市文颖设备科技有限公司 | 武汉高低温试验机-现货恒温恒湿试验箱-高低温湿热交变箱价格-湖北高天试验设备 | 定硫仪,量热仪,工业分析仪,马弗炉,煤炭化验设备厂家,煤质化验仪器,焦炭化验设备鹤壁大德煤质工业分析仪,氟氯测定仪 | 代写标书-专业代做标书-商业计划书代写「深圳卓越创兴公司」 | 蚂蚁分类信息系统 - PHP同城分类信息系统 - MayiCMS | 北京办公室装修,办公室设计,写字楼装修-北京金视觉装饰工程公司 北京成考网-北京成人高考网 | 石牌坊价格石牌坊雕刻制作_石雕牌坊牌楼石栏杆厂家_山东嘉祥石雕有限公司 | 葡萄酒灌装机-食用油灌装机-液体肥灌装设备厂家_青州惠联灌装机械 | 直齿驱动-新型回转驱动和回转支承解决方案提供商-不二传动 | 北京普辉律师事务所官网_北京律师24小时免费咨询|法律咨询 | 一体式钢筋扫描仪-楼板测厚仪-裂缝检测仪-泰仕特(北京) | 膜结构车棚|上海膜结构车棚|上海车棚厂家|上海膜结构公司 | 山东信蓝建设有限公司官网| 半自动预灌装机,卡式瓶灌装机,注射器灌装机,给药器灌装机,大输液灌装机,西林瓶灌装机-长沙一星制药机械有限公司 | 矿用履带式平板车|探水钻机|气动架柱式钻机|架柱式液压回转钻机|履带式钻机-启睿探水钻机厂家 | 河南卓美创业科技有限公司-河南卓美防雷公司-防雷接地-防雷工程-重庆避雷针-避雷器-防雷检测-避雷带-避雷针-避雷塔、机房防雷、古建筑防雷等-山西防雷公司 | 东亚液氮罐-液氮生物容器-乐山市东亚机电工贸有限公司 | 二手注塑机回收_旧注塑机回收_二手注塑机买卖 - 大鑫二手注塑机 二手光谱仪维修-德国OBLF光谱仪|进口斯派克光谱仪-热电ARL光谱仪-意大利GNR光谱仪-永晖检测 | 无纺布包装机|径向缠绕包装机|缠绕膜打包机-上海晏陵智能设备有限公司 | 三佳互联一站式网站建设服务|网站开发|网站设计|网站搭建服务商 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | PVC快速门-硬质快速门-洁净室快速门品牌厂家-苏州西朗门业 | 低合金板|安阳低合金板|河南低合金板|高强度板|桥梁板_安阳润兴 北京租车牌|京牌指标租赁|小客车指标出租 | 精准猎取科技资讯,高效阅读科技新闻_科技猎| 小型UV打印机-UV平板打印机-大型uv打印机-UV打印机源头厂家 |松普集团 | 自动部分收集器,进口无油隔膜真空泵,SPME固相微萃取头-上海楚定分析仪器有限公司 | CTAB,表面活性剂1631溴型(十六烷基三甲基溴化铵)-上海升纬化工原料有限公司 | 防伪溯源|防窜货|微信二维码营销|兆信_行业内领先的防伪防窜货数字化营销解决方案供应商 | 井式炉-台车式回火炉-丹阳市电炉厂有限公司 | TPM咨询,精益生产管理,5S,6S现场管理培训_华谋咨询公司 | 耐酸碱胶管_耐腐蚀软管总成_化学品输送软管_漯河利通液压科技耐油耐磨喷砂软管|耐腐蚀化学软管 | 深圳法律咨询【24小时在线】深圳律师咨询免费 | 大型多片锯,圆木多片锯,方木多片锯,板材多片锯-祥富机械有限公司 | 电销卡 防封电销卡 不封号电销卡 电话销售卡 白名单电销卡 电销系统 外呼系统 | 南京蜂窝纸箱_南京木托盘_南京纸托盘-南京博恒包装有限公司 |