概述

线上项目发布一般有以下几种方案:

  1. 停机发布
  2. 蓝绿部署
  3. 滚动部署
  4. 灰度发布

停机发布 这种发布一般在夜里或者进行大版本升级的时候发布,因为需要停机,所以现在大家都在研究 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 动态路由同时存在时取并集。

  1. 访问 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, 测试结果一致。

  1. 创建 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动态路由的更多相关文章

  1. springcloud3(五) spring cloud gateway动态路由的四类实现方式

    写这篇博客主要是为了汇总下动态路由的多种实现方式,没有好坏之分,任何的方案都是依赖业务场景需求的,现在网上实现方式主要有: 基于Nacos, 基于数据库(PosgreSQL/Redis), 基于Mem ...

  2. 通过Nacos动态刷新Spring Cloud Gateway的路由

    通过Nacos动态刷新Spring Cloud Gateway的路由 一.背景 二.解决方案 三.实现功能 四.实现步骤 1.网关服务的实现 1.pom文件 2.bootstrap.yml配置文件 3 ...

  3. Spring Cloud Gateway 动态修改请求参数解决 # URL 编码错误传参问题

    Spring Cloud Gateway 动态修改请求参数解决 # URL 编码错误传参问题 继实现动态修改请求 Body 以及重试带 Body 的请求之后,我们又遇到了一个小问题.最近很多接口,收到 ...

  4. Spring Cloud Alibaba学习笔记(17) - Spring Cloud Gateway 自定义路由谓词工厂

    在前文中,我们介绍了Spring Cloud Gateway内置了一系列的路由谓词工厂,但是如果这些内置的路由谓词工厂不能满足业务需求的话,我们可以自定义路由谓词工厂来实现特定的需求. 例如有某个服务 ...

  5. spring cloud gateway网关路由分配

    1, 基于父工程,新建一个模块 2,pom文件添加依赖 <dependencies> <dependency> <groupId>org.springframewo ...

  6. Spring Cloud Alibaba学习笔记(16) - Spring Cloud Gateway 内置的路由谓词工厂

    Spring Cloud Gateway路由配置的两种形式 Spring Cloud Gateway的路由配置有两种形式,分别是路由到指定的URL以及路由到指定的微服务,在上文博客的示例中我们就已经使 ...

  7. Spring cloud gateway 如何在路由时进行负载均衡

    本文为博主原创,转载请注明出处: 1.spring cloud gateway 配置路由 在网关模块的配置文件中配置路由: spring: cloud: gateway: routes: - id: ...

  8. Spring cloud gateway

    ==================================为什么需要API gateway?==================================企业后台微服务互联互通, 因为 ...

  9. Spring Cloud Gateway服务网关

    原文:https://www.cnblogs.com/ityouknow/p/10141740.html Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gatewa ...

  10. 网关服务Spring Cloud Gateway(一)

    Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢?Zuul(1.x) 基于 Servlet,使 ...

随机推荐

  1. unittest实战(一):用例框架

    import unittest class forTest0(unittest.TestCase): @classmethod def setUpClass(cls) -> None: prin ...

  2. 为XHR对象所有方法和属性提供钩子 全局拦截AJAX

    摘要 ✨长文 阅读约需十分钟 ✨跟着走一遍需要一小时以上 ✨约100行代码 前段时间打算写一个给手机端用的假冒控制台 可以用来看console的输出 这一块功能目前已经完成了 但是后来知道有一个腾讯团 ...

  3. 零基础JavaScript编码(三)总结

    任务目的 在上一任务基础上继续JavaScript的体验 接触一下JavaScript中的高级选择器 学习JavaScript中的数组对象遍历.读写.排序等操作 学习简单的字符串处理操作 任务描述 参 ...

  4. java线程组

    1 简介 一个线程集合.是为了更方便地管理线程.父子结构的,一个线程组可以集成其他线程组,同时也可以拥有其他子线程组. 从结构上看,线程组是一个树形结构,每个线程都隶属于一个线程组,线程组又有父线程组 ...

  5. win10查看本机mac地址的详细操作

    今天和大家分享win10查看本机mac地址的方法,mac地址是什么东西?MAC地址实际上就是网卡的一个标识,和身份证号码类似,大多数情况下是不需要关心MAC地址是多少的,一般不能改动,所以也不会重复. ...

  6. 关于SSH与SSM的组成及其区别

    前言 当下SpringBoot盛行,咱再聊聊SpringBoot盛行之前的框架组合,当做复习巩固哈. 在聊之前,得先说说MVC,MVC全名是Model View Controller,是模型(mode ...

  7. java调用DLL,打印二维码标签

    package com.ian.das.controller; import java.util.List; import org.xvolks.jnative.JNative; import org ...

  8. CORS(cross-origin-resource-sharing)跨源资源共享

    其实就是跨域请求.我们知道XHR只能访问同一个域中的资源,这是浏览器的安全策略所限制,但是开发中合理的跨域请求是必须的.CORS是W3的一个工作草案,基本思想就是:使用自定义的HTTP头部让浏览器与服 ...

  9. iPhone UIButton图标与文字间距设置【转】

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 150, 50)]; [button setTitle:@& ...

  10. IntelliJ IDEA 2018.3 x64的破解和安装

    IntelliJ IDEA 2018.3 x64的破解和安装 前言 IntelliJ IDEA 作为一个优秀的Java开发环境,深受许多开发者喜爱,但是它的价格却贵得让人无法接受,这篇文章将介绍永久激 ...