spring-cloud-gateway動態路由的實現方法
概述
線上項目發佈一般有以下幾種方案:
- 機發佈
- 藍綠部署
- 滾動部署
- 灰度發佈
停機發佈 這種發佈一般在夜裡或者進行大版本升級的時候發佈,因為需要停機,所以現在大傢都在研究 Devops
方案。
藍綠部署 需要準備兩個相同的環境。一個環境新版本,一個環境舊版本,通過負載均衡進行切換與回滾,目的是為瞭減少服務停止時間。
滾動部署 就是在升級過程中,並不一下子啟動所有新版本,是先啟動一臺新版本,再停止一臺老版本,然後再啟動一臺新版本,再停止一臺老版本,直到升級完成。基於 k8s
的升級方案默認就是滾動部署。
灰度發佈 也叫金絲雀發佈,灰度發佈中,常常按照用戶設置路由權重,例如 90%的用戶維持使用老版本,10%的用戶嘗鮮新版本。不同版本應用共存,經常與 A/B 測試一起使用,用於測試選擇多種方案。
上邊介紹的幾種發佈方案,主要是引出我們接下來介紹的 spring-cloud-gateway
動態路由,我們可以基於動態路由、負載均衡和策略加載去實現 灰度發佈
。當然現在有很多開源的框架可以實現 灰度發佈
,這裡隻是研究學習。
動態路由
spring-cloud-gateway
默認將路由加載在內存中。具體可以參見 InMemoryRouteDefinitionRepository
類的實現。
這裡我們基於 Redis
實現動態路由。基礎項目見 spring-cloud-gateway 簡介
1. 將 actuator 的端點暴露出來。
management: endpoints: web: exposure: include: "*"
2. redis 配置
@Configuration public class RedisConfig { @Bean(name = {"redisTemplate", "stringRedisTemplate"}) public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(factory); return redisTemplate; } }
3. 將原內存路由持久化到 redis
@Component public class RedisRouteDefinitionRepository implements RouteDefinitionRepository { /** * hash存儲的key */ public static final String GATEWAY_ROUTES = "gateway_dynamic_route"; @Resource private StringRedisTemplate redisTemplate; /** * 獲取路由信息 * @return */ @Override public Flux<RouteDefinition> getRouteDefinitions() { List<RouteDefinition> routeDefinitions = new ArrayList<>(); redisTemplate.opsForHash().values(GATEWAY_ROUTES).stream() .forEach(routeDefinition -> routeDefinitions.add(JSON.parseObject(routeDefinition.toString(), RouteDefinition.class))); return Flux.fromIterable(routeDefinitions); } @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(routeDefinition -> { redisTemplate.opsForHash().put(GATEWAY_ROUTES, routeDefinition.getId(), JSONObject.toJSONString(routeDefinition)); return Mono.empty(); }); } @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap(id -> { if (redisTemplate.opsForHash().hasKey(GATEWAY_ROUTES, id)) { redisTemplate.opsForHash().delete(GATEWAY_ROUTES, id); return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException("route definition is not found, routeId:" + routeId))); }); } }
4. 重寫動態路由服務
@Service public class GatewayDynamicRouteService implements ApplicationEventPublisherAware { @Resource private RedisRouteDefinitionRepository redisRouteDefinitionRepository; private ApplicationEventPublisher applicationEventPublisher; /** * 增加路由 * @param routeDefinition * @return */ public int add(RouteDefinition routeDefinition) { redisRouteDefinitionRepository.save(Mono.just(routeDefinition)).subscribe(); applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); return 1; } /** * 更新 * @param routeDefinition * @return */ public int update(RouteDefinition routeDefinition) { redisRouteDefinitionRepository.delete(Mono.just(routeDefinition.getId())); redisRouteDefinitionRepository.save(Mono.just(routeDefinition)).subscribe(); applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); return 1; } /** * 刪除 * @param id * @return */ public Mono<ResponseEntity<Object>> delete(String id) { return redisRouteDefinitionRepository.delete(Mono.just(id)).then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build()))) .onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build())); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } }
5. 對外暴露接口
@RestController @RequestMapping("/gateway") public class GatewayDynamicRouteController { @Resource private GatewayDynamicRouteService gatewayDynamicRouteService; @PostMapping("/add") public String create(@RequestBody RouteDefinition entity) { int result = gatewayDynamicRouteService.add(entity); return String.valueOf(result); } @PostMapping("/update") public String update(@RequestBody RouteDefinition entity) { int result = gatewayDynamicRouteService.update(entity); return String.valueOf(result); } @DeleteMapping("/delete/{id}") public Mono<ResponseEntity<Object>> delete(@PathVariable String id) { return gatewayDynamicRouteService.delete(id); } }
測試
測試前刪除我們配置的靜態路由,因為靜態路由和 redis 動態路由同時存在時取並集。
訪問 http://localhost:2000/actuator/gateway/routes , 可以看到隻有默認路由。
[ { "route_id": "CompositeDiscoveryClient_consul", "route_definition": { "id": "CompositeDiscoveryClient_consul", "predicates": [ { "name": "Path", "args": { "pattern": "/consul/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/consul/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://consul", "order": 0 }, "order": 0 }, { "route_id": "CompositeDiscoveryClient_idc-gateway", "route_definition": { "id": "CompositeDiscoveryClient_idc-gateway", "predicates": [ { "name": "Path", "args": { "pattern": "/idc-gateway/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/idc-gateway/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://idc-gateway", "order": 0 }, "order": 0 }, { "route_id": "CompositeDiscoveryClient_idc-provider1", "route_definition": { "id": "CompositeDiscoveryClient_idc-provider1", "predicates": [ { "name": "Path", "args": { "pattern": "/idc-provider1/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/idc-provider1/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://idc-provider1", "order": 0 }, "order": 0 }, { "route_id": "CompositeDiscoveryClient_idc-provider2", "route_definition": { "id": "CompositeDiscoveryClient_idc-provider2", "predicates": [ { "name": "Path", "args": { "pattern": "/idc-provider2/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/idc-provider2/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://idc-provider2", "order": 0 }, "order": 0 } ]
這個時候訪問 http://192.168.124.5:2000/idc-provider1/provider1/1 根據結果可以推測能正確路由到 provider1
, 測試結果一致。
創建 provider1
路由,將路徑設置為 /p1/**
,測試是否生效。
POST
請求 http://localhost:2000/gateway/add
{ "id":"provider1", "predicates":[ { "name":"Path", "args":{ "_genkey_0":"/p1/**" } }, { "name":"RemoteAddr", "args":{ "_genkey_0":"192.168.124.5/16" } } ], "filters":[ { "name":"StripPrefix", "args":{ "_genkey_0":"1" } } ], "uri":"lb://idc-provider1", "order":0 }
查看 redis
存儲,或者請求 http://localhost:2000/actuator/gateway/routes , 都可以看到配置成功。
訪問
curl http://localhost:2000/p1/provider1/1
結果輸出 2001,與期望一致。
由此可見動態路由已經生效。
到此這篇關於spring-cloud-gateway動態路由的實現方法的文章就介紹到這瞭,更多相關spring-cloud-gateway動態路由內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringCloud Gateway使用redis實現動態路由的方法
- Spring Cloud Gateway動態路由Apollo實現詳解
- nacos gateway動態路由實戰
- SpringCloud Gateway 路由配置定位原理分析
- 詳解Spring Cloud Gateway修改請求和響應body的內容